692

How to set the current working directory in Python?

martineau
  • 119,623
  • 25
  • 170
  • 301
Ricardo Rod
  • 8,453
  • 9
  • 27
  • 39

4 Answers4

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
  • 7
    Can 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
  • 19
    I 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
Community
  • 1
  • 1
dinesh
  • 1,037
  • 7
  • 2
  • 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
  • 3
    The `\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
  • 2
    You 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