pathlib 是一个面向对象的文件系统路径模块。下面是我是用较多的函数和使用方法:

快速食用方法

导入模块

from pathlib import Path

新建一个Path对象

dstbinPath = Path(inputPath)

获取文件所在的相对路径上级路径

rootPath = Path.cwd().parent

parent属性可以链式调用,比如

Path.cwd().parent.parent.parent.parent

Path对象的parents属性可以拿到各级目录列表(索引值越大越接近root)

拼接路径

logPath = Path.joinpath(rootPath, 'errorlog')

遍历文件夹文件

for sub in logPath.iterdir():
    if sub.is_file():
        # 获取文件的绝对路径
        srcPath = sub.resolve()

判断文件后缀扩展名

if logfile.suffix == '.json':

删除文件

file.unlink()

对应的 os 模块的工具

os 和 os.path pathlib
os.path.abspath() Path.resolve()
os.chmod() Path.chmod()
os.mkdir() Path.mkdir()
os.makedirs() Path.mkdir()
os.rename() Path.rename()
os.replace() Path.replace()
os.rmdir() Path.rmdir()
os.remove(), os.unlink() Path.unlink()
os.getcwd() Path.cwd()
os.path.exists() Path.exists()
os.path.expanduser() Path.expanduser()Path.home()
os.listdir() Path.iterdir()
os.path.isdir() Path.is_dir()
os.path.isfile() Path.is_file()
os.path.islink() Path.is_symlink()
os.link() Path.link_to()
os.symlink() Path.symlink_to()
os.readlink() Path.readlink()
os.stat() Path.stat(), Path.owner(), Path.group()
os.path.isabs() PurePath.is_absolute()
os.path.join() PurePath.joinpath()
os.path.basename() PurePath.name
os.path.dirname() PurePath.parent
os.path.samefile() Path.samefile()
os.path.splitext() PurePath.suffix