2019-03-04 Python pathlib介绍(持续完善中)

三种操作系统windows、Mac 和 Linux

不同的操作系统,文件连接所用正反斜线是不一致的。

Windows filenames:
C:\some_folder\some_file.txt

Most other operating systems:
/some_folder/some_file.txt

三种不同的拼接路径的方式

  • 手动拼接
data_folder = "source_data/text_files/"

file_to_open = data_folder + "raw_data.txt"

f = open(file_to_open)

print(f.read())

这样写,你不能让每个操作系统都能顺利执行。

  • os.path 模块
import os.path

data_folder = os.path.join("source_data", "text_files")

file_to_open = os.path.join(data_folder, "raw_data.txt")

f = open(file_to_open)

print(f.read())

此代码可以在各个平台顺利运行,但是反复使用os.path.join很啰嗦

  • pathlib模块(Python3的标准支持)
    python3.4+ 都自带标准库pathlib,所以不需要再通过pip3 安装
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())

不用open读文件 file.read_text()

from pathlib import Path

data_folder = Path("source_data/text_files/")

file_to_open = data_folder / "raw_data.txt"

print(file_to_open.read_text())

文件及路径操作

from pathlib import Path

filename = Path("source_data/text_files/raw_data.txt")

print(filename.name)
# prints "raw_data.txt"

print(filename.suffix)
# prints "txt"

print(filename.stem)
# prints "raw_data"

if not filename.exists():
    print("Oops, file doesn't exist!")
else:
    print("Yay, the file exists!")

参考资料
https://zhuanlan.zhihu.com/p/33524938

你可能感兴趣的:(2019-03-04 Python pathlib介绍(持续完善中))