使用 pathlib 更好地處理路徑
pathlib 是 Python 3 的預設模組,幫助避免使用大量的 os.path.join()。
from pathlib import Path dataset = `wiki_images` datasets_root = Path(`/path/to/datasets/`) train_path = datasets_root / dataset / `train` test_path = datasets_root / dataset / `test` for image_path in train_path.iterdir(): with image_path.open() as f: # note, open is a method of Path object # do something with an image
拼接操作符:/
Path物件 / Path物件
Path物件 / 字串
字串 / Path物件
分解
parts屬性,可以返回路徑中的每一部分
joinpath
joinpath(*other)連線多個字串到Path物件中
其他方法
p.exists() p.is_dir() p.parts p.with_name(`sibling.png`) # only change the name, but keep the folder p.with_suffix(`.jpg`) # only change the extension, but keep the folder and the name p.chmod(mode) p.rmdir()