Python标准库系列之pathlib模块

首先我们看使用OS模块连接目录和文件

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模块

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可以直接读取文件而不需要open

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://docs.python.org/3/library/pathlib.html
参考原文: https://zhuanlan.zhihu.com/p/33524938

你可能感兴趣的:(Python标准库系列之pathlib模块)