Python路径处理库pathlib

pathlib 模块提供了文件路径对象抽象,不仅仅是替换 os.path 模块对文件的操作,可以说是路径处理的瑞士军刀。

这里写图片描述

This module offers classes representing filesystem paths with semantics appropriate for different operating systems. Path classes are divided between pure paths, which provide purely computational operations without I/O, and concrete paths, which inherit from pure paths but also provide I/O operations.

其中最常使用的就是 Path 类,因为它与具体系统无关。

pathlib.PurePath

分割路径 parts

类似 os.path.split(),但返回元组。


p = PurePath('/usr/bin/python3').parts  # ('/', 'usr', 'bin', 'python3')

PureWindowsPath('c:/Program Files/PSF').parts  # ('c:\\', 'Program Files', 'PSF')

驱动器 drive

返回驱动器名称,主要面向 Windows 系统。


PureWindowsPath('c:/Program Files/').drive  # 'c:'

PureWindowsPath('/Program Files/').drive  # ''

PurePosixPath('/etc').drive  # ''

根目录 root

返回路径的根目录,面向 Unix/Linux 系统。


PureWindowsPath('c:/Program Files/').root  # '\\'

PureWindowsPath('c:Program Files/').root  # ''

PureWindowsPath('//host/share').root  # '\\'

PurePosixPath('/etc').root  # '/'

自动判断驱动器或根目录 anchor


PureWindowsPath('c:/Program Files/').anchor  # 'c:\\'

PureWindowsPath('c:Program Files/').anchor  # 'c:'

PurePosixPath('/etc').anchor  # '/'

PureWindowsPath('//host/share').anchor  # '\\\\host\\share\\'

所有上级目录列表 parents

返回所有上级(祖先)目录列表,[上级目录, 上上级目录, …, 根目录]


PureWindowsPath('c:/foo/bar/setup.py').parents  

# [PureWindowsPath('c:/foo/bar'), PureWindowsPath('c:/foo'), PureWindowsPath('c:/')]

父目录 parent

返回父目录


PurePosixPath('/a/b/c/d').parent  # PurePosixPath('/a/b/c')

注意相对路径问题:


PurePosixPath('/').parent  # PurePosixPath('/')

PurePosixPath('.').parent  # PurePosixPath('.')

PurePosixPath('foo/..').parent  # PurePosixPath('foo')

在遇到相对路径时,在获取父目录之前调用 Path.resolve() 消除符号链接和 .. 之类表示。

完整文件名 name

返回除驱动器或根目录外完整文件名(带文件名后缀)。


PurePosixPath('my/library/setup.py').name  # 'setup.py'

PureWindowsPath('//some/share/setup.py').name  # 'setup.py'

PureWindowsPath('//some/share').name  # ''

文件后缀 suffix

返回文件扩后缀,没有扩展名则返回空串。


PurePosixPath('my/library/setup.py').suffix  # '.py'

PurePosixPath('my/library.tar.gz').suffix  # '.gz'

PurePosixPath('my/library').suffix  # ''

文件后缀列表 suffixes

当文件有多个后缀,返回文件所有后缀列表;没有则返回空列表。


PurePosixPath('my/library.tar.gar').suffixes  # ['.tar', '.gar']

PurePosixPath('my/library.tar.gz').suffixes  # ['.tar', '.gz']

PurePosi
  • 15
    点赞
  • 65
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值