Python3中pathlib

python学习网 2018-12-26 08:51:02

使用 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()

了解更多

推荐阅读

阅读(7588) 评论(0)