Change directory to the directory of a Python script
Question:
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].
Answers:
os.chdir(os.path.dirname(__file__))
Sometimes __file__
is not defined, in this case you can try sys.path[0]
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.
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) )
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].
os.chdir(os.path.dirname(__file__))
Sometimes __file__
is not defined, in this case you can try sys.path[0]
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.
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) )