18

How do I change directory to the directory with my Python script in? So far, I figured out I should use os.chdir and sys.argv[0]. I'm sure there is a better way then to write my own function to parse argv[0].

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • You can directly copy-paste this: `import os; os.chdir(os.path.dirname(__file__))` – Basj Feb 11 '18 at 21:52
  • 1
    Possible duplicate of [How do I change directory (cd) in Python?](https://stackoverflow.com/q/431684/608639) – jww Jan 31 '19 at 00:23
  • 1
    This is **not** a duplicate, this question here is specific to change to the working script's dir, it's not a general question about "how to `cd` in Python" – Basj Jul 26 '22 at 15:54
  • For future reference: in the case of a cython-`--embed` .exe, `__file__` does not work. `sys.path[0]` works but it is the path of the `python38.zip` package (containing all modules) as it is usual in the case of an embedded install. – Basj Jul 26 '22 at 15:57

4 Answers4

32
os.chdir(os.path.dirname(__file__))
ayrnieu
  • 1,839
  • 14
  • 15
  • for whatever reason __file__ was C:\dev\Python25\Lib\idlelib so a quick replace with argv[0] solved it. +1 and check marked –  Feb 04 '09 at 03:07
  • 1
    Also, depending on platform you may want to use `os.path.abspath` on the result of `os.path.dirname` to make sure any symbolic links or other filesystem redirection get expanded properly. – James Bennett Feb 04 '09 at 07:16
  • Example of case when `os.path.abspath` is needed: https://stackoverflow.com/questions/509742/change-directory-to-the-directory-of-a-python-script#comment129152389_23595382 – Basj Jul 26 '22 at 16:02
16

os.chdir(os.path.dirname(os.path.abspath(__file__))) should do it.

os.chdir(os.path.dirname(__file__)) would not work if the script is run from the directory in which it is present.

iamas
  • 311
  • 2
  • 7
  • 1
    It also works to write `os.chdir(os.path.dirname(__file__) or '.')`. The in-directory problem arises when `__file__` is not prefixed with `./`. `os.path.dirname` returns an empty string in that case. – George Aug 03 '14 at 20:12
  • Nice observation @George :) – iamas Oct 17 '14 at 15:09
  • Example of case when `os.path.abspath` is needed: you call the script on Windows from a .bat file: `python myscript.py`. Then `abspath` is mandatory. – Basj Jul 26 '22 at 16:02
7

Sometimes __file__ is not defined, in this case you can try sys.path[0]

2

on windows OS, if you call something like python somefile.py this os.chdir(os.path.dirname(__file__)) will throw a WindowsError. But this should work for all cases:

import os
absFilePath = os.path.abspath(__file__)
os.chdir( os.path.dirname(absFilePath) )
Scott 混合理论
  • 2,263
  • 8
  • 34
  • 59