要获取包含 Python 文件的目录的完整路径,请在该文件中写入:
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
(请注意,如果您已经使用 os.chdir()
更改当前工作目录,则上述咒语将不起作用,因为 __file__
常量的值是相对于当前工作目录的,并且不会被 {1 } 称呼。)
要获取当前工作目录,请使用
import os
cwd = os.getcwd()
上面使用的模块、常量和函数的文档参考:
os 和 os.path 模块。
__file__ 常量
os.path.realpath(path)(返回“指定文件名的规范路径,排除路径中遇到的任何符号链接”)
os.path.dirname(path) (返回“路径名路径的目录名”)
os.getcwd() (返回“代表当前工作目录的字符串”)
os.chdir(path) ("改变当前工作目录为路径")
Current working directory:os.getcwd()
__file__
attribute 可以帮助您找出正在执行的文件所在的位置。这篇 Stack Overflow 帖子解释了一切:How do I get the path of the current executed file in Python?
作为参考,您可能会发现这很有用:
import os
print("Path at terminal when executing this file")
print(os.getcwd() + "\n")
print("This file path, relative to os.getcwd()")
print(__file__ + "\n")
print("This file full path (following symlinks)")
full_path = os.path.realpath(__file__)
print(full_path + "\n")
print("This file directory and name")
path, filename = os.path.split(full_path)
print(path + ' --> ' + filename + "\n")
print("This file directory only")
print(os.path.dirname(full_path))
__file__
在这里表示什么?它对我不起作用。
__file__
是模块对象的属性。您需要在 Python 文件中运行代码,而不是在 REPL 上。
pathlib
模块 introduced in Python 3.4 (PEP 428 — The pathlib module — object-oriented filesystem paths) 使与路径相关的体验变得更好。
pwd
/home/skovorodkin/stack
tree
.
└── scripts
├── 1.py
└── 2.py
要获取当前工作目录,请使用 Path.cwd()
:
from pathlib import Path
print(Path.cwd()) # /home/skovorodkin/stack
要获取脚本文件的绝对路径,请使用 Path.resolve()
方法:
print(Path(__file__).resolve()) # /home/skovorodkin/stack/scripts/1.py
要获取脚本所在目录的路径,请访问 .parent
(建议在 .parent
之前调用 .resolve()
):
print(Path(__file__).resolve().parent) # /home/skovorodkin/stack/scripts
请记住,__file__
在某些情况下并不可靠:How do I get the path of the current executed file in Python?。
请注意,Path.cwd()
、Path.resolve()
和其他 Path
方法返回路径对象(在我的例子中为 PosixPath
),而不是字符串。在 Python 3.4 和 3.5 中造成了一些痛苦,因为 open
内置函数只能与字符串或字节对象一起使用,并且不支持 Path
对象,因此您必须将 Path
对象转换为字符串或使用Path.open()
方法,但后一个选项需要您更改旧代码:
文件脚本/2.py
from pathlib import Path
p = Path(__file__).resolve()
with p.open() as f: pass
with open(str(p)) as f: pass
with open(p) as f: pass
print('OK')
输出
python3.5 scripts/2.py
Traceback (most recent call last):
File "scripts/2.py", line 11, in <module>
with open(p) as f:
TypeError: invalid file: PosixPath('/home/skovorodkin/stack/scripts/2.py')
如您所见,open(p)
不适用于 Python 3.5。
PEP 519 — Adding a file system path protocol 在 Python 3.6 中实现,向 open
函数添加了对 PathLike
对象的支持,因此现在您可以将 Path
对象直接传递给 open
函数:
python3.6 scripts/2.py
OK
app_path = Path(__file__).resolve().parent.parent.parent
与 ../../../
并行使用。
python3.5
”和“python3.6
”的可执行文件(或等效文件)? Ubuntu Ubuntu MATE 20.04 (Focal Fossa) 没有(至少默认情况下没有)。它具有名称为“python3
”和“python2
”的可执行文件(但不是“python
” - 这会导致 some things to break)
python3.x
符号链接。也许我认为它会使片段对读者更清楚一些。
获取当前目录全路径 >>import os >>print os.getcwd() 输出:"C :\Users\admin\myfolder" 单独获取当前目录文件夹名 >>import os >>str1=os.getcwd () >>str2=str1.split('\\') >>n=len(str2) >>print str2[n-1] 输出:“myfolder”
os.getcwd().split('\\')[-1]
Pathlib 可用于获取包含当前脚本的目录:
import pathlib
filepath = pathlib.Path(__file__).resolve().parent
app_path = Path(__file__).resolve().parent.parent.parent
与 ../../../
并行使用。
如果您尝试查找当前所在文件的当前目录:
操作系统不可知的方式:
dirname, filename = os.path.split(os.path.abspath(__file__))
如果您使用的是 Python 3.4,则有全新的高级 pathlib
模块,它允许您方便地调用 pathlib.Path.cwd()
来获取代表当前工作目录的 Path
对象,以及许多其他新功能。
有关此新 API 的更多信息,请参阅 here。
pathlib2
:pypi.python.org/pypi/pathlib2
获取当前目录完整路径:
os.path.realpath('.')
os.getcwd()
和 `os.path.realpath('.') 返回完全相同的字符串路径。
回答#1:
如果您想要当前目录,请执行以下操作:
import os
os.getcwd()
如果您只需要任何文件夹名称并且您有该文件夹的路径,请执行以下操作:
def get_folder_name(folder):
'''
Returns the folder name, given a full folder path
'''
return folder.split(os.sep)[-1]
回答#2:
import os
print os.path.abspath(__file__)
我认为查找当前执行上下文名称的最简洁方法是:
current_folder_path, current_folder_name = os.path.split(os.getcwd())
如果您正在搜索当前执行脚本的位置,您可以使用 sys.argv[0]
获取完整路径。
sys.argv[0]
不必包含执行脚本的完整 路径。
对于问题 1,使用 os.getcwd() # Get working directory
和 os.chdir(r'D:\Steam\steamapps\common') # Set working directory
我建议对问题 2 使用 sys.argv[0]
,因为 sys.argv
是不可变的,因此总是返回当前文件(模块对象路径)并且不受 os.chdir()
的影响。你也可以这样做:
import os
this_py_file = os.path.realpath(__file__)
# vvv Below comes your code vvv #
但是,当 PyInstaller 编译时,该代码段和 sys.argv[0]
将不起作用或工作异常,因为魔术属性未在 __main__
级别设置,并且 sys.argv[0]
是调用可执行文件的方式(这意味着它会受到工作目录)。
不定期副业成功案例分享
dirname
反转realpath
时,路径通常是相同的,但当文件(或其目录)实际上是符号链接时,路径会有所不同。NameError: name '__file__' is not defined
。如何解决这个问题?