tags:

views:

60

answers:

2

Hi all. What is the best way to represent a windows directory, for example "C:\meshes\as"? I have been trying to modify a script but it never works because I can't seem to get the directory right, I assume because of the '\' acting as escape character?

Thanks, Gareth

+3  A: 

Use the os.path module.

os.path.join( "C:", "meshes", "as" )

Or use raw strings

r"C:\meshes\as"
S.Lott
os.path.join may not behave as you expect when a component is a drive letter, since relative paths are allowed even then. (The result of the first line is 'C:meshes\\as' on Windows.)
dash-tom-bang
+6  A: 

you can use always:

'C:/mydir'

this works both in linux and windows. Other posibility is

'C:\\mydir'

if you have problems with some names you can also try raw strings:

r'C:\mydir'

however best practice is to use the os.path module functions that always select the correct configuration for your OS:

os.path.join(mydir, myfile)
joaquin
Thanks guys, '/' worked fine, but the other hints are appreciated.
Gareth
@Gareth, I am very lazy and often found myself using '/'. However in the long run the use of os.path is more convenient. It also allows you to use mydir and myfile as variables that you can easily modify.
joaquin
The only thing to be careful with on raw strings is that they can't end with \
Douglas Leeder