将目录更改为 Python 脚本的目录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/509742/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 20:16:06  来源:igfitidea点击:

Change directory to the directory of a Python script

pythonscriptingdirectory

提问by ayrnieu

How do i change directory to the directory with my python script in? So far I figured out I should use os.chdirand sys.argv[0]. I'm sure there is a better way then to write my own function to parse argv[0].

如何将目录更改为包含我的 python 脚本的目录?到目前为止,我想我应该使用os.chdirand sys.argv[0]。我确信有更好的方法来编写我自己的函数来解析 argv[0]。

回答by ayrnieu

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

回答by iamas

os.chdir(os.path.dirname(os.path.abspath(__file__)))should do it.

os.chdir(os.path.dirname(os.path.abspath(__file__)))应该这样做。

os.chdir(os.path.dirname(__file__))would not work if the script is run from the directory in which it is present.

os.chdir(os.path.dirname(__file__))如果脚本是从它所在的目录运行的,则将不起作用。

回答by iamas

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

有时__file__是没有定义的,这种情况你可以试试sys.path[0]

回答by u1230329

on windows OS, if you call something like python somefile.pythis os.chdir(os.path.dirname(__file__))will throw a WindowsError. But this should work for all cases:

在 Windows 操作系统上,如果你调用类似python somefile.py 的东西,这个os.chdir(os.path.dirname(__file__))会抛出一个 WindowsError。但这应该适用于所有情况:

import os
absFilePath = os.path.abspath(__file__)
os.chdir( os.path.dirname(absFilePath) )