Change directory to the directory of a Python script [duplicate]

本秂侑毒 提交于 2020-01-10 10:24:48

问题


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


回答1:


os.chdir(os.path.dirname(__file__))



回答2:


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.




回答3:


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




回答4:


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) )


来源:https://stackoverflow.com/questions/509742/change-directory-to-the-directory-of-a-python-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!