helexy22 / helexy22.github.com

🐭Agile Learning based on GitHub , KEEP Retrospection and Introspection! Inspired by@jimmylv. My blog-->
https://helexy22.github.io
MIT License
0 stars 0 forks source link

Python 解决 Windows 文件名反斜杠 #19

Open helexy22 opened 5 years ago

helexy22 commented 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())

在这里,有两点需要注意:

其他

tags: