Open helexy22 opened 5 years ago
要想让你的 Python 代码同时在 Windows 和 Mac/Linux 上工作,你需要处理不同系统文件名用不同斜杠的问题。
微软 Windows 系统在文件夹名之间使用反斜杠字符,而几乎所有其它的计算机(操作系统)都使用正斜杠。
Python 3 有一个名为「pathlib」的新模块,使得用户处理文件几乎没有任何困难 「pathlib」模块链接:https://docs.python.org/3/library/pathlib.html 要使用该库,你只需使用正斜杠将一个路径或文件名传给一个新的「Path()」对象,然后它将处理余下的操作:
from pathlib import Path data_folder = Path("source_data/text_files/") file_to_open = data_folder / "raw_data.txt" f = open(file_to_open) print(f.read())
在这里,有两点需要注意:
我们可以在无需打开和关闭文件的情况下,读取文本文件的内容
「pathlib」使大多数标准的文件操作变得快速而简单
可以使用「pathlib」显式地将一个「Unix」路径转化为一个「Windows」格式的路径
参考来源:Windows文件名非用反斜杠?Python小技巧帮你解决这个麻烦 | 机器之心 https://www.jiqizhixin.com/articles/2019-07-21-2
原文链接:https://medium.com/@ageitgey/python-3-quick-tip-the-easy-way-to-deal-with-file-paths-on-windows-mac-and-linux-11a072b58d5f
tags:
需求
要想让你的 Python 代码同时在 Windows 和 Mac/Linux 上工作,你需要处理不同系统文件名用不同斜杠的问题。
微软 Windows 系统在文件夹名之间使用反斜杠字符,而几乎所有其它的计算机(操作系统)都使用正斜杠。
解决方案
Python 3 有一个名为「pathlib」的新模块,使得用户处理文件几乎没有任何困难 「pathlib」模块链接:https://docs.python.org/3/library/pathlib.html 要使用该库,你只需使用正斜杠将一个路径或文件名传给一个新的「Path()」对象,然后它将处理余下的操作:
在这里,有两点需要注意:
其他
我们可以在无需打开和关闭文件的情况下,读取文本文件的内容
「pathlib」使大多数标准的文件操作变得快速而简单
可以使用「pathlib」显式地将一个「Unix」路径转化为一个「Windows」格式的路径
参考来源:Windows文件名非用反斜杠?Python小技巧帮你解决这个麻烦 | 机器之心 https://www.jiqizhixin.com/articles/2019-07-21-2
原文链接:https://medium.com/@ageitgey/python-3-quick-tip-the-easy-way-to-deal-with-file-paths-on-windows-mac-and-linux-11a072b58d5f
tags: