Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python os.chdir is modifying the passed directory name

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?

like image 344
Josh Wood Avatar asked Jun 26 '13 17:06

Josh Wood


People also ask

What does chdir do in Python?

chdir() method in Python used to change the current working directory to specified path. It takes only a single argument as new directory path. Parameters: path: A complete path of directory to be changed to new directory path.

What do the functions OS Getcwd () and OS chdir () do?

Check and Set Your Working Directory Using OS getcwd() : CWD stands for Current Working Directory. This function allows you to see what your current working directory is. chdir("path-to-dir") : Short for CHange DIRectory, this function allows you to set the current working directory to a path of your choice.

How do you reset the working directory in Python?

To change the current working directory in Python, use the chdir() method. The method accepts one argument, the path to the directory to which you want to change. The path argument can be absolute or relative.

Which module has a method for changing the current working directory?

Python's os module provides a function to change the current working directory i.e. It changes the current working directory to the given path. First print the current working directory using os. getcwd() i.e.


1 Answers

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")
like image 135
voithos Avatar answered Sep 19 '22 17:09

voithos