$ cat scripts/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')
15 回答
如果您要查找当前所在文件的当前目录:
OS不可知的方式:
为了查看以下脚本的当前工作目录类型:
问题1使用
os.getcwd() # get working dir
和os.chdir(r'D:\Steam\steamapps\common') # set working dir
我建议在问题2中使用
sys.argv[0]
因为sys.argv
是不可变的,因此总是返回当前文件(模块对象路径)而不受os.chdir()
的影响 . 你也可以这样做:但是,当PyInstaller编译时,该片段和
sys.argv[0]
将无法正常工作或工作,因为魔法属性未在__main__
级别设置,sys.argv[0]
是您调用exe的方式(意味着它受工作目录的影响) .如果要搜索当前执行脚本的位置,可以使用
sys.argv[0]
获取完整路径 .在Python 3.4(PEP 428 — The pathlib module — object-oriented filesystem paths)中,pathlib module,introduced使路径相关的体验变得更好 .
要获取当前工作目录Path.cwd():
要获取脚本文件的绝对路径,请使用Path.resolve()方法:
要获取脚本所在目录的路径,请访问.parent(建议在
.parent
之前调用.resolve()
):请记住,
__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()方法,但后者选项要求你改变旧代码:如您所见
open(p)
不适用于Python 3.5 .PEP 519 — Adding a file system path protocol,在Python 3.6中实现,将PathLike对象的支持添加到open函数,所以现在可以直接将
Path
对象传递给open
函数:要获取包含Python文件的目录的完整路径,请在该文件中写入:
(请注意,上面的咒语已经't work if you'已使用
os.chdir()
来更改当前的工作目录,因为__file__
常量的值是相对于当前工作目录的,并且不会被os.chdir()
调用更改 . )要使用当前工作目录
上面使用的模块,常量和函数的文档参考:
os和os.path模块 .
file常数
os.path.realpath(path)(返回"the canonical path of the specified filename, eliminating any symbolic links encountered in the path")
os.path.dirname(path)(返回“路径名
path
的目录名”)os.getcwd()(返回"a string representing the current working directory")
os.chdir(path)(“将当前工作目录更改为
path
”)派对有点晚了,但我认为找到当前执行上下文名称的最简洁方法是
当前工作目录:os.getcwd()
file attribute可以帮助您找出您正在执行的文件所在的位置 . 这篇SO帖子解释了一切:How do I get the path of the current executed file in Python?
可以使用Pathlib来获取包含当前脚本的目录:
Answer to #1:
如果需要当前目录,请执行以下操作:
如果您只想要任何文件夹名称并且您拥有该文件夹的路径,请执行以下操作:
Answer to #2:
1.获取当前目录的完整路径
o / p:“C:\ Users \ admin \ myfolder”
1.单独获取当前目录文件夹名称
O / P: “MyFolder文件”
如果您使用的是Python 3.4,那么有一个全新的更高级
pathlib
模块,它允许您方便地调用pathlib.Path.cwd()
以获得表示当前工作目录的Path
对象以及许多其他新功能 .有关此新API的更多信息,请访问here .
要获取当前目录的完整路径:
在python中获取工作目录 . 您可以使用以下代码:
您可能会发现这有用作为参考: