10

I am trying to change the current working directory in python using os.chdir. I have the following code:

import os

os.chdir("C:\Users\Josh\Desktop\20130216")

However, when I run it, it seems to change the directory, as it comes out with the following error message:

Traceback (most recent call last):
File "C:\Users\Josh\Desktop\LapseBot 1.0\LapseBot.py", line 3, in <module>
os.chdir("C:\Users\Josh\Desktop\20130216")
WindowsError: [Error 2] The system cannot find the file specified
  'C:\\Users\\Josh\\Desktop\x8130216'

Can anyone help me?

vyi
  • 1,078
  • 1
  • 19
  • 46
Josh Wood
  • 1,598
  • 3
  • 16
  • 21

5 Answers5

28

Python is interpreting the \2013 part of the path as the escape sequence \201, which maps to the character \x81, which is ü (and of course, C:\Users\Josh\Desktopü30216 doesn't exist).

Use a raw string, to make sure that Python doesn't try to interpret anything following a \ as an escape sequence.

os.chdir(r"C:\Users\Josh\Desktop\20130216")
voithos
  • 68,482
  • 12
  • 101
  • 116
4

You could also use os.path.join (documentation). Example:

os.chdir(os.path.join('C:\Users\Josh\Desktop', '20130216'))

This is more elegant + it's compatible with different operating systems.

vaultah
  • 44,105
  • 12
  • 114
  • 143
3

This should work -

os.chdir("C:\Users\Josh\Desktop\\20130216")
masnun
  • 11,635
  • 4
  • 39
  • 50
  • why do you need the second backslash? – Stephan Jun 26 '13 at 17:12
  • 1
    @Stephan Because "\201" is a character. We need to escape the backslash to tell python that you didn't mean that but it's just another backslash (in fact path separator here) – masnun Jun 26 '13 at 17:15
0

There are two to use os.chdir():

  1. If you are using raw string than use single backslash \:

    os.chdir(r"C:\Users\Josh\Desktop\20130216")

or

  1. If you are not using raw string than use double backslash \\

    os.chdir("C:\Users\Josh\Desktop\20130216")

phd
  • 82,685
  • 13
  • 120
  • 165
Anas Khan
  • 1
  • 1
-1

I have faced the same problem but you have to try:

os.chdir(c:\\user\\Josh\\Desktop)

Use \\ so maybe you should get your solution.