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].
Asked
Active
Viewed 1.8k times
15
Forge
- 6,228
- 6
- 42
- 60
-
You can directly copy-paste this: `import os; os.chdir(os.path.dirname(__file__))` – Basj Feb 11 '18 at 21:52
-
1Possible duplicate of [How do I change directory (cd) in Python?](https://stackoverflow.com/q/431684/608639) – jww Jan 31 '19 at 00:23
4 Answers
27
os.chdir(os.path.dirname(__file__))
ayrnieu
- 1,769
- 13
- 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
-
1Also, 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
14
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
- 191
- 1
- 7
-
1It 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
-
7
Sometimes __file__ is not defined, in this case you can try sys.path[0]
-
2
-
3
-
1
-
This is true, yet irrelevant to the question, because context is outside 'Python script'. – tishma May 14 '22 at 12:12
1
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,172
- 8
- 32
- 59