对于习惯了使用os模块操作文件和文件夹路径的朋友来说,下表给出了一一对应的关系,建议收藏。
os.path.abspath Path.resolve
os.chmod Path.chmod
os.mkdir 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.expanduserand Path.home
os.path.isdir Path.is_dir
os.path.isfile Path.is_file
os.path.islink Path.is_symlink
os.stat Path.stat, Path.owner,
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
小结
pathlib是一个比os.path更优秀的库,它以面向对象的编程方式来表示和处理文件系统路径。它支持直接使用"/"拼接路径,并支持链式查询,代码比os.path更简洁。Python 3.6和Django 3.1后建议使用pathlib库处理文件系统路径。