【问题标题】:Using pathlib.Path on MacOS to escape Windows paths correctly在 MacOS 上使用 pathlib.Path 正确转义 Windows 路径
【发布时间】:2020-07-19 05:08:25
【问题描述】:

在 MacOS 上,我正在扫描网络驱动器,其中包含多个目录,这些目录是从 Windows 卷开始的硬盘驱动器的完整副本。

例子:

file_path = pathlib.Path("/Volumes/fotos/hd2/Old 160gig HD/Pictures/Location/Location Pictures/100MEDIA/Dalan\'s Desert")

如果我使用 Python 的 subprocess 运行类似 subprocess.run(["open", file_path]) 的东西,我会收到以下错误:

The file /Volumes/fotos/hd2/Old 160gig HD/Pictures/Location/Location Pictures/100MEDIA/Dalan\'s Desert does not exist

如果我注释掉撇号和/或空格,我会得到可变的成功,但它似乎不一致?我也尝试使用 shell=True 进行此操作,但似乎找不到 100% 有效的解决方案。

在 Python 中处理路径以使它们始终在 MacOS 上下文中工作的规范方法是什么?

【问题讨论】:

  • 试试这个;从 pathlib 导入路径、PureWindowsPath、PurePosixPath;如果您想要 Windows 约定,请使用 PureWindowsPath() 将其转换为 pathlib 对象,然后将其传递给 Path() 以进行转换并在下一行使用它;

标签: python macos path


【解决方案1】:

我们可以参考docs;一开始的第一个image也很有帮助;

In [1]: from pathlib import Path, PureWindowsPath, PurePosixPath                                                                                                                                                                                            

In [2]: PureWindowsPath(Path("/Volumes/fotos/hd2/Old 160gig HD/Pictures/Location/Location Pictures/100MEDIA/Dalan\'s Desert"))                                                                                                                              
Out[2]: PureWindowsPath("/Volumes/fotos/hd2/Old 160gig HD/Pictures/Location/Location Pictures/100MEDIA/Dalan's Desert")

In [3]: PurePosixPath(Path("/Volumes/fotos/hd2/Old 160gig HD/Pictures/Location/Location Pictures/100MEDIA/Dalan\'s Desert"))                                                                                                                                
Out[3]: PurePosixPath("/Volumes/fotos/hd2/Old 160gig HD/Pictures/Location/Location Pictures/100MEDIA/Dalan's Desert")

【讨论】:

  • 我看不出PureWindowsPathPurePosixPath 有什么区别?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-21
  • 1970-01-01
  • 2022-10-18
  • 1970-01-01
相关资源
最近更新 更多