[Tutor] os.chdir() will not accept string variable

Steve Willoughby steve at alchemy.com
Sat Apr 16 03:13:47 CEST 2011


On 15-Apr-11 18:00, Rodney Lewis wrote:
> I cannot get os.chdir() to accept inputData[0].  os.chdir() works as
> expected in the interpreter when I put the little 'r' before the exact
> same string but as a literal, e.g.: r"F:\Music\Siouxsie and the
> Banshees\the rapture"

It's because the string in inputData[0] has a trailing newline.

> WindowsError: [Error 123] The filename, directory name, or volume
> label syntax is incorrect 'F:\\Music\\Siouxsie and the Banshees\\the
> rapture\n'
>
> Why is it doubling the backslashes and adding '\n' to the end?  How do

The actual string value is:
	F:\Music\Sousie and the Banshees\the rapture<newline>

When printing it out to you in the error message, Python REPRESENTED 
that string TO YOU with extra backslash codes so you could see what was 
in the sring:
	F:\\Music\\Sousie and the Banshees\\the rapture\n

The extra backslashes aren't really in the string.  Your problem is that 
readlines() retains the end-of-line character in the lines it reads, 
which is not actually part of the filename, so os.chdir() doesn't like it.

You'll need to strip off the newlines from the strings you read before 
giving them to os.chdir().

> I make it stop?  What does the little 'r' mean before a string literal
> and how do I do the same for a string variable?

It means not to interpret (most) backslash codes in the string as it's 
compiled from your source code into the internal string data managed by 
the program.  If you wanted to put that string literally in your source 
code, you could do either of these:
	'F:\\Music\\Sousie and the Banshees\\the rapture'
or	r'F:\Music\Sousie and the Banshees\the rapture'

But that's not your problem in this case.  You don't need this when 
reading in lines of data from another source, since they wouldn't get 
the same backslash interpretation as source lines do.

>
> # mdf -- mp3datafixer
>
> import glob, os
>
> def mdf():
>      inputFile = open( 'mdfinputs.txt', 'r' )
>      inputData = inputFile.readlines()
>      inputFile.close()
>
>      os.chdir( r'%s' % inputData[0] )
>      newNames = []
>      oldNames = glob.glob( '*.*' )
>      for index, item in enumerate( oldNames ):
>          print index, item
>
> if __name__ == '__main__':
>      mdf()
>      raw_input( "\nPress 'enter' to close console window:" ) # Keeps
> console window open in Windows
>
> Thanks!
>
>


-- 
Steve Willoughby / steve at alchemy.com
"A ship in harbor is safe, but that is not what ships are built for."
PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C


More information about the Tutor mailing list