# pathlib.Path()
from pathlib import Path p=Path("/test2")
# Path.cwd()
print(p.cwd()) /py3
# Path.home()
print(p.home()) /root
# Path.iterdir()
print(list(p.iterdir())) [PosixPath(‘/test2/p.py‘), PosixPath(‘/test2/aa.txt‘), PosixPath(‘/test2/bb‘)]
# Path.stat()
print(p.stat()) s.stat_result(st_mode=16804, st_ino=296353, st_dev=2053, st_nlink=3, st_uid=500, st_gid=500, st_size=4096, st_atime=1503619754, st_mtime=1503523284, st_ctime=1503523284)
# Path.chmod()
print(oct(p.stat().st_mode)[-3:]) 644 p.chmod(0o755) print(oct(p.stat().st_mode)[-3:]) 755
# Path.owner()
print(p.owner()) user00
# Path.group()
print(p.group()) user00
# Path.glob(pattern)
print(list(p.glob("*.py"))) [PosixPath(‘/test2/p.py‘)] print(list(p.glob(‘**/*.py‘))) [PosixPath(‘/test2/p.py‘), PosixPath(‘/test2/bb/p2.py‘)]
# Path.rglob(pattern)
print(list(p.rglob(‘*.py‘))) [PosixPath(‘/test2/p.py‘), PosixPath(‘/test2/bb/p2.py‘)]
# Path.expanduser()
p=Path("~/Desktop") print(p.expanduser()) /root/Desktop
# Path.exists()
print(p.exists()) True p=Path("/test2_not_exist")print(p.exists()) False
# Path.is_dir() | is_file()
print(p.is_dir()) True print(p.is_file()) False
# Path.is_socket() | is_fifo() | is_block_device() | is_char_device() | is_symlink()
# Path.mkdir(mode=0o777, parents=False, exist_ok=False)
p=Path("/test2/test2_tree") p.mkdir(mode=0o644) print(p.exists()) True p=Path("/test2_no_exist/aa") p.mkdir() FileNotFoundError: [Errno 2] No such file or directory: ‘/test2_no_exist/aa‘ p.mkdir(parents=True) print(p.exists()) True p.mkdir(exist_ok=True) 不会报错
# Path.touch(mode=0o666, exist_ok=True)
p=Path("/test2/no_exits_text") p.touch(mode=0o755) print(p.exists()) True print(oct(p.stat().st_mode)[-3:]) 755
# Path.open(mode=’r’, buffering=-1, encoding=None, errors=None, newline=None)
p=Path("/test2/aa.txt") with p.open() as f: print(f.read())
# Path.read_bytes()
print(p.read_bytes()) b‘test content\n2test2 content\n‘
# Path.read_text()
print(p.read_text()) test content 2test2 content
# Path.write_bytes(data)
# Path.write_text(data,encoding=None,errors=None)
# Path.rename(target)p=Path("/test2/test.txt")
p.open("w").write("test content") target=Path("/test2/test.rename") p.rename(target) print(target.open().read()) test content print(p.exists()) False
# Path.replace(target)
无条件替换
# Path.resolve()
返回绝对路径
# Path.samefile(other_path)
# Path.rmdir()
p=Path("/test2/bb") p.rmdir() OSError: [Errno 39] Directory not empty: ‘/test2/bb‘ #只能删除空目录
# Path.symlink_to()
# Path.unlink()
# PurePath.suffix
p=Path("/test2/bb/p2.py") print(p.suffix) .py print(p.suffixes) [‘.py‘]
时间: 2024-10-11 16:36:15