Python os.chdir is modifying the passed directory name

40,370

Solution 1

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")

Solution 2

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.

Solution 3

This should work -

os.chdir("C:\Users\Josh\Desktop\\20130216")
Share:
40,370
Josh Wood
Author by

Josh Wood

Updated on July 14, 2020

Comments

  • Josh Wood
    Josh Wood almost 4 years

    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?

  • Stephan
    Stephan about 11 years
    why do you need the second backslash?
  • masnun
    masnun about 11 years
    @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)
  • Martijn Pieters
    Martijn Pieters about 11 years
    Or use forward slashes, or double the backslashes.
  • voithos
    voithos about 11 years
    @MartijnPieters: Yep, good point. Python can correctly understand paths like C:/Users/Josh/... on Windows.
  • Nabin
    Nabin over 10 years
    what does the "r" do??
  • voithos
    voithos over 10 years
    @Nabin It's how you define a raw string, i.e. a string without any escape sequences