21

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].

4
  • 1
    You can directly copy-paste this: import os; os.chdir(os.path.dirname(__file__)) Commented Feb 11, 2018 at 21:52
  • 1
    Possible duplicate of How do I change directory (cd) in Python? Commented Jan 31, 2019 at 0: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" Commented Jul 26, 2022 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. Commented Jul 26, 2022 at 15:57

5 Answers 5

36
os.chdir(os.path.dirname(__file__))
Sign up to request clarification or add additional context in comments.

3 Comments

for whatever reason file was C:\dev\Python25\Lib\idlelib so a quick replace with argv[0] solved it. +1 and check marked
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.
Example of case when os.path.abspath is needed: stackoverflow.com/questions/509742/…
17

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.

4 Comments

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.
Nice observation @George :)
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.
Works, but so ugly and poorly readable!!
7

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

4 Comments

@Miki - when is __file__ not defined?
@RobBednark: python3.3 -c "print(__file__)"
@JanusTroelsen: Also true for Python 2.7.
This is true, yet irrelevant to the question, because context is outside 'Python script'.
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) )

Comments

0
import os
if __name__ == "__main__": # import this_file will not change cwd
    os.chdir(os.path.dirname(__file__))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.