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].
5 Answers
os.chdir(os.path.dirname(__file__))
3 Comments
James Bennett
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.Basj
Example of case when
os.path.abspath is needed: stackoverflow.com/questions/509742/…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
George
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.iamas
Nice observation @George :)
Basj
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.xjcl
Works, but so ugly and poorly readable!!
Sometimes __file__ is not defined, in this case you can try sys.path[0]
4 Comments
Rob Bednark
@Miki - when is
__file__ not defined?Janus Troelsen
@RobBednark:
python3.3 -c "print(__file__)"George
@JanusTroelsen: Also true for Python 2.7.
tishma
This is true, yet irrelevant to the question, because context is outside 'Python script'.
import os; os.chdir(os.path.dirname(__file__))cdin Python"--embed.exe,__file__does not work.sys.path[0]works but it is the path of thepython38.zippackage (containing all modules) as it is usual in the case of an embedded install.