If you mean the directory of the script being run:
(如果您表示正在运行的脚本目录:)
import os
os.path.dirname(os.path.abspath(__file__))
If you mean the current working directory:
(如果您的意思是当前工作目录:)
import os
os.getcwd()
Note that before and after file
is two underscores, not just one.
(请注意, file
前后分别是两个下划线,而不仅仅是下划线。)
Also note that if you are running interactively or have loaded code from something other than a file (eg: a database or online resource), __file__
may not be set since there is no notion of "current file".
(另请注意,如果您正在交互运行或已从文件以外的内容(例如数据库或在线资源)中加载了代码,则可能不会设置__file__
因为没有“当前文件”的概念。)
The above answer assumes the most common scenario of running a python script that is in a file. (上面的答案假设运行文件中的python脚本的最常见情况。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…