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

  

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

拼接操作符:/

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

了解更多

推荐阅读

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄