篇首语:本文由小编为大家整理,主要介绍了[PY3]——IO——pathlib相关的知识,希望对你有一定的参考价值。
# pathlib.Path()
from pathlib import Pathp=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:])644p.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())Truep=Path("/test2_not_exist")
print(p.exists())False
# Path.is_dir() | is_file()
print(p.is_dir())Trueprint(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())Truep=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())Truep.mkdir(exist_ok=True)不会报错
# Path.touch(mode=0o666, exist_ok=True)
p=Path("/test2/no_exits_text")p.touch(mode=0o755)print(p.exists())Trueprint(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 2test2 content "
# Path.read_text()
print(p.read_text())test content2test2 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 contentprint(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).pyprint(p.suffixes)[".py"]
以上是关于[PY3]——IO——pathlib的主要内容,如果未能解决你的问题,请参考以下文章