How to set the current working directory in Python?
Asked
Active
Viewed 1.1M times
4 Answers
992
Try os.chdir
import os os.chdir(path)
Change the current working directory to path. Availability: Unix, Windows.

Anders Lindén
- 6,839
- 11
- 56
- 109

Mark Byers
- 811,555
- 193
- 1,581
- 1,452
-
7Can you give me an example of format of the path? I am using os x; when I am trying to set a path I am getting an error - >>> import os >>> os.chdir(Users/Me/Desktop/M/PTS/Python/t1.py) File "
", line 1 os.chdir(/Users/Me/Desktop/M/PTS/Python/t1.py) ^ SyntaxError: invalid syntax >>> – Pooja25 Nov 04 '15 at 20:48 -
4@Pooja25 The path must be a string. in addition, chdir expects a directory name, but you are specifying a file. – mwil.me Jan 14 '16 at 01:25
-
19I usually use `os.getcwd()` first, and that shows me the format of the accepted input for `os.chdir()`. – Rani Kheir Apr 21 '16 at 09:22
152
Perhaps this is what you are looking for:
import os
os.chdir(default_path)

unutbu
- 842,883
- 184
- 1,785
- 1,677
69
import os
print os.getcwd() # Prints the current working directory
To set the working directory:
os.chdir('c:\\Users\\uname\\desktop\\python') # Provide the new path here
-
76–1: This answer is not useful — *because it was already posted six years ago.* – jwodder Jan 24 '16 at 03:47
-
6@cpb2 Semicolons at the end of a statement are not a syntax error in Python. You can even use them to put multiple statements on one line D-: But they are certainly very bad style. – Arthur Tacca Oct 27 '16 at 07:56
-
3The `\u` in the string on the other hand *is* a syntax error; that should be `\\u`. – Arthur Tacca Oct 28 '16 at 13:28
-
2@jwodder - I agree with you. OTOH, there are at least 24 people for which this was useful. Perhaps it was the fact that he covered ítems in the comments of the accepted answer: 1) format of explicit paths, 2) how to get examples of such (with `getcwd`).... remarkable. – sancho.s ReinstateMonicaCellio Jul 27 '17 at 07:42
-
2You need double slashes for each directory level when dealing with Windows. – SDsolar Aug 02 '17 at 04:19
14
It work for Mac also
import os
path="/Users/HOME/Desktop/Addl Work/TimeSeries-Done"
os.chdir(path)
To check working directory
os.getcwd()

PritamJ
- 337
- 4
- 10
-
`Python` one of the core ideas of python is to work cross-plattform. – user1767754 Dec 20 '17 at 17:10
-
Thanks for this example, I was trying (the usual) ``"~/etc"`` without success. – PatrickT Apr 15 '18 at 09:52
-
3@PatrickT if you want to expand `~`, you need to use `os.path.expanduser("~/etc")`, which will then expand to the full path (`/path/to/homedir/etc`) – Aaron D May 30 '18 at 13:29