Hey Guys, i just started learning python and havent really done much programming so im pretty new

im following a book and I have to read some data from a text file

the code thats giving me trouble is

os.chdir('Users\spreston\Desktop\HeadFirst\Chapter 3')

the error says that the path does not exist, but i know it does, which leads me to believe i typed the path in wrong, any suggestions?

Recommended Answers

The best way is to always use raw string(r) when give path in windows.
There is also an option to use \\ or /.

So this do not work.
os.chdir('C:\test')
This work.

os.chdir(r'C:\test')
os.chdir('C:\\test')
os.chdir('C:/test')

The reason why is this way,is that a singel backslashes(\) in python can(do) get read as …

Jump to Post

All 7 Replies

Guessing here, but maybe you need to give the full absolute path:
'C:\Users\spreston\Desktop\HeadFirst\Chapter 3'

assuming that is what the full absolute path is, of course

no that doesnt work either, the C: produces an error as well, a unicode error. Its the colon that throws it off it seems

If your path doesn't start with a drive letter or a (back- or forward-)slash, it's interpreted relative to the current directory. So Chophouse is right, you need to make your path absolute unless Users is a subdirectory of your current directory.

You also need to escape your backslashes or use forward-slashes instead. Otherwise \U is interpreted as the beginning of a unicode escape sequence, which is why you got a unicode error.

oh ok. well why does windows display the file paths using back slashes

You can try this too

import os
p = os.path.join('C:\\', 'Users', 'spreston', 'Desktop', 'HeadFirst', 'Chapter 3')

The best way is to always use raw string(r) when give path in windows.
There is also an option to use \\ or /.

So this do not work.
os.chdir('C:\test')
This work.

os.chdir(r'C:\test')
os.chdir('C:\\test')
os.chdir('C:/test')

The reason why is this way,is that a singel backslashes(\) in python can(do) get read as an escape character.
@sepp2k also metion that you need escape your backslashes.
Take a look at this.

>>> s = 'C:\test'
>>> print s
C:  est
>>> print repr(s)
'C:\test'
>>> repr(s)
"'C:\\test'"

Then with raw string.

>>> s = r'C:\test'
>>> print s
C:\test
>>> print repr(s)
'C:\\test'
>>> repr(s)
"'C:\\\\test'"

One more \

>>> s = 'C:\\test'
>>> print s
C:\test

My preferred way is to use the module I uploaded in this post

from whatever import path    
p = path("C:")/"foo"/"bar"/"qux"

Although usually I don't call it 'module whatever' but module 'kernilis.path'.