Python 如何获取 pathlib.Path 对象的绝对路径?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42513056/
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
How to get absolute path of a pathlib.Path object?
提问by EquipDev
Making a path object with pathlib
module like:
使用pathlib
模块制作路径对象,例如:
p = pathlib.Path('file.txt')
The p
object will point to some file in the filesystem, since I can do for example p.read_text()
.
该p
对象将指向文件系统中的某个文件,因为我可以做例如p.read_text()
.
How can I get the absolute path of the p
object in a string?
如何获取p
字符串中对象的绝对路径?
Appears that I can use for example os.path.abspath(p)
to get the absolute path, but it awkward to use an os.path
method, since I assume that pathlib
should be a replacement for os.path
.
似乎我可以使用例如os.path.abspath(p)
获取绝对路径,但使用os.path
方法很尴尬,因为我认为它pathlib
应该是os.path
.
回答by florisla
Use resolve()
使用解决()
Simply use Path.resolve()like this:
只需像这样使用Path.resolve():
p = p.resolve()
This makes your path absolute and replaces all relative parts with absolute parts, and all symbolic links with physical paths. On case-insensitive file systems, it will also canonicalize the case (file.TXT
becomes file.txt
).
这将使您的路径成为绝对路径,并用绝对部分替换所有相关部分,并用物理路径替换所有符号链接。在不区分大小写的文件系统上,它还将规范化大小写 ( file.TXT
become file.txt
)。
Avoid absolute()
避免绝对()
You should not useabsolute()
because it's not documented, untested, and considered for removal. (See the discussion in the bug reportcreated by @Jim Fasarakis Hilliard).
您不应该使用absolute()
它,因为它没有记录、未经测试和考虑删除。(请参阅@Jim Fasarakis Hilliard 创建的错误报告中的讨论)。
The difference
区别
The difference between resolve
and absolute
is that absolute() does not replace the symbolically linked (symlink) parts of the path, and it never raises FileNotFoundError
. It does not modify the case either.
resolve
和之间的区别在于absolute
absolute() 不会替换路径的符号链接(符号链接)部分,并且它永远不会引发FileNotFoundError
。它也不会修改案例。
If you want to avoid resolve()
(e.g. you want to retain symlinks, casing, or relative parts) then use this instead:
如果您想避免resolve()
(例如,您想保留符号链接、大小写或相关部分),请改用:
p = Path.cwd() / "file.txt"
Beware non-existing file on Windows
当心 Windows 上不存在的文件
If the file does not exist, in Python 3.6+ on Windows, resolve() does not prepend the current working directory. See issue 38671.
如果文件不存在,在 Windows 上的 Python 3.6+ 中,resolve() 不会在当前工作目录之前。请参阅问题 38671。
Beware FileNotFoundError
当心 FileNotFoundError
On Python versions predating v3.6, resolve()
doesraise a FileNotFoundError
if the path is not present on disk.
在Python版本早于V3.6,resolve()
并提出一个FileNotFoundError
如果路径不存在在磁盘上。
So if there's any risk to that, either check beforehand with p.exists()
or try/catch the error.
因此,如果有任何风险,请事先检查p.exists()
或尝试/捕获错误。
# check beforehand
if p.exists():
p = p.resolve()
# or except afterward
try:
p = p.resolve()
except FileNotFoundError:
# deal with the missing file here
pass
If you're dealing with a path that's not on disk, to begin with, and you're not on Python 3.6+, it's best to revert to os.path.abspath(str(p))
.
如果您正在处理不在磁盘上的路径,首先,并且您不是在 Python 3.6+ 上,最好恢复到os.path.abspath(str(p))
.
From 3.6 on, resolve()
only raises FileNotFoundError
if you use the strict
argument.
从 3.6 开始,resolve()
只有FileNotFoundError
在使用strict
参数时才会引发。
# might raise FileNotFoundError
p = p.resolve(strict=True)
But beware, using strict
makes your code incompatible with Python versions predating 3.6 since those don't accept the strict
argument.
但请注意, usingstrict
会使您的代码与 3.6 之前的 Python 版本不兼容,因为它们不接受strict
参数。
The future
未来
Follow issue 39090to follow documentation changes related to absolute()
.
关注问题 39090以关注与absolute()
.
回答by Dimitris Fasarakis Hilliard
You're looking for the method .absolute
, if my understanding is correct, who's documentation states:
您正在寻找方法.absolute
,如果我的理解是正确的,谁的文档说明:
>>> print(p.absolute.__doc__)
Return an absolute version of this path. This function works
even if the path doesn't point to anything.
No normalization is done, i.e. all '.' and '..' will be kept along.
Use resolve() to get the canonical path to a file.
With a test file on my system this returns:
在我的系统上有一个测试文件,这将返回:
>>> p = pathlib.Path('testfile')
>>> p.absolute()
PosixPath('/home/jim/testfile')
This methodseems to be a new, and still, undocumented addition to Path
and Path
inheritting objects.
这个方法似乎是一个新的,仍然是未记录的添加Path
和Path
继承对象的方法。
回答by Veech
If you simply want the path and do not want to check if the file exists, you can do
如果您只是想要路径并且不想检查文件是否存在,您可以这样做
str(p)
as document in the Operationssection.
作为操作部分中的文档。
回答by Peter
pathlib.Path.cwd() / p
This is recommended by CPython core developersas the "one obvious way".
这是CPython 核心开发人员推荐的“一种明显的方式”。
p.resolve()
does not return an absolute path for non-existing files on Windows at least.
p.resolve()
至少不会为 Windows 上不存在的文件返回绝对路径。
p.absolute()
is undocumented.
p.absolute()
是无证的。