Ban*_*ach 5 python python-3.x pathlib
如何检查pathlib.Path是否指向同一文件系统位置?
我希望我可以使用.samefile,但是当文件/目录尚不存在时,这不起作用。
简单==似乎也不起作用:Path("test/../file")!=Path("file")
编辑:即使Path("test/../file").resolve().absolute()!=Path("file").resolve().absolute()在一般情况下(例如,当我在网络驱动器上运行它时,前者解析为//networkaddress/file,后者解析为Z:/file
由于在您的情况下,它只是可能尚不存在的给定路径的基本名称,因此您可以通过解析父级然后连接回基本名称来标准化路径:
def normalize_path(path):
return path.parent.resolve().joinpath(path.name)
Run Code Online (Sandbox Code Playgroud)
以便:
normalize_path(Path('test/../file')) == normalize_path(Path('file'))
Run Code Online (Sandbox Code Playgroud)
True如果test作为常规目录存在则返回。
演示: https: //replit.com/@blhsing1/HardtofindEquatorialParallelcomputing