Python os module won't recognize particular folder in directory

Viewed 495

I am trying to use several of the functions in the os module to navigate and manipulate files in a directory but I'm running into some confusing and frustrating issues. Python will let me navigate to some folders, throw an error for others. For example, for this block of code,

import os
os.chdir('C:\Python27\root_folder')

I get an error:

OSError: [WinError 123] The filename, directory name, or volume label syntax 
is incorrect: 'C:\\Python27\root_folder'

But when I run this:

os.chdir('C:\Python27\Lib')

There are no issues. Lib and root_folder are both folders in this directory, as you can see Here, but for some reason, one is recognized by python and the other is not. I have tried renaming the folder several times, deleting and creating a new one, all to no avail. I feel like the solution must be painfully obvious but I can't figure it out. This same exact problem arises when I use other os functions, like os.walk.

Oh, and I know that the directory is called Python27, but I'm running Python 3.6.1, if that makes any difference.

Any help is appreciated

1 Answers

You need to make all the backslashes double.

os.chdir('C:\\Python27\\root_folder')

Python interprets backslashes followed by a letter in strings as special characters. For example

\newline    Backslash and newline ignored
\'  Single quote (')     
\"  Double quote (")     
\a  ASCII Bell (BEL)     
\b  ASCII Backspace (BS)     
\f  ASCII Formfeed (FF)  
\n  ASCII Linefeed (LF)  
\r  ASCII Carriage Return (CR)   
\t  ASCII Horizontal Tab (TAB)   
\v  ASCII Vertical Tab (VT)
\ooo    Character with octal value ooo
\xhh    Character with hex value hh

there may be a couple others, but \P and \L are not special, so are just interpreted as a backslash followed by a P and a backslash followed by an L. but in the other, \r is interpreted as a carriage return, rather than a backslash followed by a r.

Related