简体   繁体   中英

Weird Path in Python `pathlib` resolution that doesn't exist in system

I'll jump in medias res to the code:

from pathlib import Path
import os
p = Path(os.getenv("APPDATA")).joinpath(r"Microsoft\WindowsApps")

p.resolve()  # gives 'C:/Users/Alex/AppData/Local/Packages/PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0/LocalCache/Roaming/Microsoft/WindowsApps' 

Why is this happening? The system says that there is no such path p , I check hidden files, not even a symbolic link. Why is it resolved to that path?

Path.resolve() just makes the path an absolute path, if you want to also check if the resolved path is an existing path you need to set Path.resolve(strict=True) or a call .exists() on the resolved path.

https://docs.python.org/3/library/pathlib.html#pathlib.Path.resolve

E:

Tested this on my machine in blocks and seems to working as expected:

from pathlib import Path
import os

p = Path(os.getenv("APPDATA"))
print(p)
p = p.joinpath(r"Microsoft\WindowsApps")
print(p)
p = p.resolve()
print(p)
p = p.joinpath("..")
print(p)
p = p.resolve()
print(p)

Output:

C:\Users\tzane\AppData\Roaming
C:\Users\tzane\AppData\Roaming\Microsoft\WindowsApps
C:\Users\tzane\AppData\Roaming\Microsoft\WindowsApps
C:\Users\tzane\AppData\Roaming\Microsoft\WindowsApps\..
C:\Users\tzane\AppData\Roaming\Microsoft

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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