pathlib — Object-oriented filesystem paths — Python 3.10.0 documentation
和 os 对比
os and os.path | pathlib |
---|---|
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.expanduser and 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, 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 |
os.path.expanduser('~') | Path.home |
CheatSheet

Demo
from pathlib import Path
def print_path() -> None:
'''目录相关'''
print(f'当前目录:{Path.cwd()}')
print(f'当前用户home目录:{Path.home()}')
print(f'当前文件目录(相对路径):{Path(__file__)}')
print(f'当前文件目录(绝对路径):{Path(__file__).resolve()}')
print(f'目录拼接(/): {Path.cwd() / "log" / "debug.log"}')
print(f'目录拼接(joinpath):{Path.cwd().joinpath("log","debug.log")}')
def print_iter() -> None:
'''目录遍历'''
cwd = Path.cwd()
print(f'遍历当前目录: {[path for path in cwd.iterdir()]}')
print(f'当前目录下文件后缀:{[f.suffix for f in cwd.iterdir() if f.is_file()]}') # is_path()
print(f'当前目录下搜索指定后缀文件(.py): {list(cwd.glob("*.py"))}')
def print_file() -> None:
'''文件相关'''
file = Path(__file__)
print(f'size: {file.stat().st_size}')
print(f'atime: { file.stat().st_atime}')
print(f'ctime: {file.stat().st_ctime}')
print(f'mtime: {file.stat().st_mtime}')
print(f'文件名: {file.name}')
print(f'文件名(不含后缀):{file.stem}')
print(f'后缀:{file.suffix}')
print(f'父级目录:{file.parent}')
print(f'文件是否存在: {file.exists} ')
def main() -> None:
print_path()
print_file()
print_iter()
if __name__ == "__main__":
main()
网友评论