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

后端 未结 4 1224
暗喜
暗喜 2021-02-03 16:56

Making a path object with pathlib module like:

p = pathlib.Path(\'file.txt\')

The p object will point to some file in

4条回答
  •  野性不改
    2021-02-03 17:29

    Use resolve()

    Simply use Path.resolve() like this:

        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).

    Avoid absolute()

    You should not use absolute() because it's not documented, untested, and considered for removal. (See the discussion in the bug report created by @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.

    If you want to avoid resolve() (e.g. you want to retain symlinks, casing, or relative parts) then use this instead:

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

    Beware non-existing file on Windows

    If the file does not exist, in Python 3.6+ on Windows, resolve() does not prepend the current working directory. See issue 38671.

    Beware FileNotFoundError

    On Python versions predating v3.6, resolve() does raise a FileNotFoundError if the path is not present on disk.

    So if there's any risk to that, either check beforehand with p.exists() or try/catch the error.

        # 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)).

    From 3.6 on, resolve() only raises FileNotFoundError if you use the strict argument.

        # 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.

    The future

    Follow issue 39090 to follow documentation changes related to absolute().

提交回复
热议问题