Path 对象和 in 运算符

判断

  • Path.is_absolute()
  • Path.is_relative_to(*other)
  • Path.is_reserved()
  • Path.match(pattern)

    • 通配符匹配

      • eg: '*.py'
  • Path.exists()
  • Path.samefile(other: Path)
  • Path.is_dir()
  • Path.is_file()
  • Path.is_symlink()
  • Path.is_mount()
  • Path.is_socket()
  • Path.is_fifo()
  • Path.is_block_device()
  • Path.is_char_device()

修改组分(返回新 Path)

  • Path.with_name(name)

    • 替换 basename
  • Path.with_stem(stem)

    • 替换 stem (除去 suffix 部分)
  • Path.with_suffix(suffix)

    • 替换 suffix 最后一个扩展名

转换

  • Path.as_posix()

    • 转换成 posix (unix) 风格, 使用'/' 分割
  • Path.as_uri()

    • 转换成 file:///etc/passwd 或 file:///c/Windows 风格,适合浏览器
  • Path.relative_to(*other)

    • 变成相对路径
  • os.fspath(Path_obj) -> str

    • 把 Path 对象转换成 系统支持的风格

组分提取(Path 属性)

  • basename 名称操作

    • Path.suffix: str
    • Path.suffixes: List[str]
    • Path.stem: str
    • Path.name: str
  • parent 父路径

    • Path.parent: Path
    • Path.parent: 类似 List[Path]
    • Path.anchor
    • Path.root
    • Path.drive
  • 拆分

    • Path.parts: List[str]

      • Path('/usr/bin/python3').parts –> ('/', 'usr', 'bin', 'python3')

创建

  • 类创建

    • pathlib.Path(*parts)
    • pathlib.PosixPath(*parts)
    • pathlib.WindowsPath(*parts)
  • 方法创建

    • Path.joinpath(*other)
    • Path.relative_to(*other)
  • 操作符创建

    • '/'

      • Path('/etc/hello') / 'file.txt' –> Path('/etc/hello/file.txt')

快捷操作 和 home 操作

  • Path.expanduser()

    • 陷阱

      • Path('~/.ssh').exists() –> False
      • Path('~/.ssh').expanduser().exists() –> True
  • Path.home()
  • Path.cwd()

状态

  • Path.stat()
  • Path.chmod(…)
  • Path.group()
  • Path.owner()

读写

  • Path.open(…)

    • 类似 open(file, …)
  • Path.read_bytes()
  • Path.write_bytes(data)
  • Path.read_text(…)
  • Path.write_text(…)
  • Path.read()
  • Path.write(…)

软链接 symlink

  • Path.symlink_to(target: Path)

    • 被链接到 target
  • Path.readlink() -> Path

    • 返回 target
  • Path.resolve()

    • 解析 '.' 、'..' (相对路径) 和 symlink
  • Path.lstat()
  • Path.lchmod(..)

硬链接 hard link

  • Path.link_to(target)

shell 操作--复制、重命名,删除

  • Path.rename(target)

    • Path 重命名成 target, 即复制为 target
  • Path.replace(target)

    • 替换当前 Path 成 target, 即用 target 覆盖
  • Path.touch()
  • Path.rmdir()

    • 删除目录
  • Path.unlink(missing_ok=False)

    • 删除文件

遍历

  • Path.iterdir()
  • Path.glob(pattern)

    • 通配符遍历
  • Path.rglob(pattern)

    • recursive Path.glob()
    • 递归遍历所有子目录