简体   繁体   English

如何获取 pathlib.Path 对象的绝对路径?

[英]How to get absolute path of a pathlib.Path object?

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的替代品。

Use resolve()使用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变为file.txt )。

Avoid absolute() before Python 3.11在 Python 3.11 之前避免使用absolute()

The alternative method absolute() was not documented or tested before Python 3.11 (See the discussion in the bug report created by @Jim Fasarakis Hilliard).替代方法absolute()在 Python 3.11 之前没有记录或测试(请参阅@Jim Fasarakis Hilliard 创建的错误报告中的讨论)。

Fixes were merged in January 2022 .修复程序于 2022 年 1 月合并。

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 . resolveabsolute之间的区别在于absolute()不会替换路径的符号链接(符号链接)部分,并且它永远不会引发FileNotFoundError It does not modify the case either.它也没有修改案例。

If you want to avoid resolve() (eg you want to retain symlinks, casing, or relative parts) then use this instead on Python <3.11:如果你想避免resolve() (例如你想保留符号链接、大小写或相关部分),那么在 Python <3.11 上使用它:

p = Path.cwd() / "file.txt"

This works even if the path you are supplying is absolute -- in that case the cwd (current working directory) is ignored.即使您提供的路径是绝对路径,这也有效——在这种情况下, cwd (当前工作目录)将被忽略。

Beware non-existing file on Windows注意 Windows 上不存在的文件

If the file does not exist, in Python 3.6 to 3.9 on Windows, resolve() does not prepend the current working directory.如果文件不存在,则在 Windows 上的 Python 3.6 到 3.9 中, resolve()不会在当前工作目录前添加。 See issue 38671 , fixed in Python 3.10.请参阅问题 38671 ,已在 Python 3.10 中修复。

Beware FileNotFoundError当心 FileNotFoundError

On Python versions predating v3.6, resolve() does raise a FileNotFoundError if the path is not present on disk.在 v3.6 之前的 Python 版本中,如果磁盘上不存在路径, 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()仅在使用strict参数时引发FileNotFoundError

# 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.但请注意,使用strict会使您的代码与 3.6 之前的 Python 版本不兼容,因为这些版本不接受strict参数。

You're looking for the method .absolute , if my understanding is correct, whose 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 method seems to be a new, and still, undocumented addition to Path and Path inheritting objects. 这种方法似乎是 PathPath继承对象的一种新的、仍然没有记录的补充。

Created an issue to document this .创建了一个问题来记录这一点

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 Operations section.作为操作部分中的文档。

pathlib.Path.cwd() / p

This isrecommended by CPython core developers as 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()没有记录。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM