0

I am trying to change directories via python, but the folder name is variable (chosen from a list):

f=open('folderlist.txt')
for line in f:

    pname = line

    os.chdir('./P574/%s' % (pname))

Which doesn't quite work because I get the error message: "No such file or directory: './folders/folder_name2\n'"

The folder names I want are in a list called "folderlist.txt", but how do I stop python adding the '\n' at the end?

Thank you!

j.w.r
  • 4,136
  • 2
  • 27
  • 29
user1551817
  • 6,693
  • 22
  • 72
  • 109
  • Take a look at http://stackoverflow.com/questions/544921/best-method-for-reading-newline-delimited-files-in-python-and-discarding-the-new – rjz Sep 05 '12 at 06:20
  • It's not being added, it's in your text file. Use line.strip() to remove the whitespace. – monkut Sep 05 '12 at 06:24

1 Answers1

2

You have to use rstrip. Change the line pname = line to

pname = line.rstrip('\n')
halex
  • 16,253
  • 5
  • 58
  • 67
  • If he wants to remove only the newline you should use `line.rstrip('\n')`, otherwise also other whitespaces are removed(which may or may not be what he wants). – Bakuriu Sep 05 '12 at 06:27