Python os.chdir is modifying the passed directory name
Asked Answered
S

5

11

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?

Stevenage answered 26/6, 2013 at 17:7 Comment(1)
Try to add another backlash before "2013"Sailer
P
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")
Pickens answered 26/6, 2013 at 17:14 Comment(4)
Or use forward slashes, or double the backslashes.Stargell
@MartijnPieters: Yep, good point. Python can correctly understand paths like C:/Users/Josh/... on Windows.Pickens
what does the "r" do??Kerns
@Kerns It's how you define a raw string, i.e. a string without any escape sequencesPickens
B
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.

Bibliomania answered 26/6, 2013 at 17:17 Comment(0)
P
3

This should work -

os.chdir("C:\Users\Josh\Desktop\\20130216")
Podesta answered 26/6, 2013 at 17:11 Comment(2)
why do you need the second backslash?Ygerne
@Ygerne 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)Podesta
A
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")

Aggappera answered 13/7, 2017 at 18:58 Comment(0)
H
-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.

Hayfork answered 23/2, 2016 at 21:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.