简体   繁体   中英

Using pathlib.Path on MacOS to escape Windows paths correctly

I am in the process of scanning through a network drive while on MacOS which contains multiple directories which are full copies of hard drives that began as Windows volumes.

Example:

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

If I use Python's subprocess to run something like subprocess.run(["open", file_path]) I get the following error:

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

I get variable success if I comment out the apostrophes and/or spaces but it doesn't seem consistent? I also attempted this with shell=True but can't seem to find a solution that works 100% of the time.

What is the canonical way within Python of handling paths so that they always work in an MacOS context?

We can refer the docs ; The first image in the very beginning is very helpful as well;

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

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