暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

python3 兼容 windows/linux/macOS 文件路径小技巧

鸡仔说 2021-05-18
1619

最近帮公司数据分析的同事配置代码的时候遇到一个很坑的问题,他的电脑是 windows 的,我的是 macOS 的,线上生产环境是 linux 的。他写完代码后要我这边去部署上线,然后发现其文件路径是这样的 "\Users\analysis\project" 。然后代码到了我的系统上就无法运行了,要改造这部分的代码。

在寻找解决方案的时候,发现了 windows 为什么一定要跟大家过不去,把反斜杠作为文件路径分隔符。原来早期 IBM 加入 DOS 开发的时候,贡献了大量的工具,他们是用斜杠表示命令行参数的,就和 linux 系统的 '-'、'- -' 一样,那斜杠被占用了,就只好选用它最相近的反斜杠作为分隔符了。
甭管历史你我他,解决 bug 全靠它——pathlib。python3 提供的 pathlib 可以非常方便的在 linux、windows、macOS 之间反复横跳。比如我们可以这样写:
from pathlib import Pathdata_folder = Path("project/resources/")file_to_open = data_folder / "sz_feb_anchor_ana.txt"with open(file_to_open) as f:     for per_line in f.readlines():         print(per_line)
这段代码在三个操作系统中都可以使用,当然这个标准库还实现了很多别的功能,比如像下面这些:
from pathlib import Pathfilename = Path("project/resources/sz_feb_anchor_ana.txt")print(filename.name)# prints "sz_feb_anchor_ana.txt"print(filename.suffix)# prints "txt"print(filename.stem)# prints "sz_feb_anchor_ana"if not filename.exists():    print("Oops, file doesn't exist!")else:    print("Yay, the file exists!")filename.is_file()# Truefilename.is_dir()# Falsefilename.parent# PosixPath('project/resources')
还有更多好玩的功能,小伙伴们可以通过传送门探索更多,就酱~
https://docs.python.org/zh-cn/3/library/pathlib.html#pathlib.Path.is_file
参考资料:

[1] Adam Geitgey (2018). Python 3 Quick Tip: The easy way to deal with file paths on Windows, Mac and Linux.

https://medium.com/@ageitgey/python-3-quick-tip-the-easy-way-to-deal-with-file-paths-on-windows-mac-and-linux-11a072b58d5f

[2] compozi(2019). 为什么Windows使用反斜杠而其他所有东西都使用正斜杠.

https://cn.compozi.com/8809-why-windows-uses-backslashes-and-everything-else-uses-forward-slashes

[3] 知乎用户(2018). Windows 的路径中表示文件层级为什么会用反斜杠 ‘\’,而 UNIX 系统都用斜杠 ‘/’?.

https://www.zhihu.com/question/19970412

以上,如果觉得内容对你有所帮助,还请点个「在看」支持,谢谢各位dai佬!



好看的人都点了在看

文章转载自鸡仔说,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论