Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
641 views
in Technique[技术] by (71.8m points)

python - 如何获取当前文件目录的完整路径?(How do I get the full path of the current file's directory?)

I want to get the current file's directory path.

(我想获取当前文件的目录路径。)

I tried:

(我试过了:)

>>> os.path.abspath(__file__)
'C:\python27\test.py'

But how can I retrieve the directory's path?

(但是如何检索目录的路径?)

For example:

(例如:)

'C:\python27\'
  ask by Shubham translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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脚本的最常见情况。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...