参考:https://docs.python.org/3/library/pathlib.html
Path
继承了PurePath
,所以Path
可以使用PurePath
的所有方法
创建path对象
方法 | 描述 |
---|---|
Path() | 构造函数 |
classmethod Path.cwd() | 获得当前工作路径对象,类似于os.getcwd() |
classmethod Path.home() | 返回用户路径对象,类似于os.path.expanduser() |
路径以及文件信息
方法 | 描述 |
---|---|
PurePath.parts | 将路径分隔开'/usr/bin/python3' -> ('/', 'usr', 'bin', 'python3') |
PurePath.drive | drive name(硬件名称,比如c盘) |
PurePath.root | 根目录 |
PurePath.anchor | 和root啥区别? |
PurePath.parents | 返回父路径的集合 |
PurePath.parent | 返回父路径 |
PurePath.name | 返回文件名 |
PurePath.suffix | 返回文件名的后缀 |
PurePath.suffixes | |
PurePath.stem | 不带后缀的文件名 |
PurePath.as_posix() | 使用/ 做分隔符 |
PurePath.as_uri() | 返回定位符 |
PurePath.is_absolute() | 是否是绝对路径 |
PurePath.is_reserved() | |
PurePath.joinpath(*other) | 连接两个路径 |
PurePath.match(pattern) | 检验是否合法 |
PurePath.relative_to(*other) | |
PurePath.with_name(name) | 更换文件名 |
PurePath.with_suffix(suffix) | 更换后缀 |
Path.glob(pattern) | 正则表示获得所有pattern,返回可迭代对象,“**”表示递归,如Path('.').glob('**/*.py') |
Path.iterdir() | 如果是directory,则迭代输出目录内容 |
Path.exists() | 是否存在file或者directory |
Path.is_dir() | 是否为directory |
Path.is_file() | 是否为file |
Path.resolve(strict=False) | 返回绝对路径 |
Path.samefile(other_path) | 是否是相同文件,等同于os.path.samestat() |
Path.stat() | 返回os.stat_result 对象,类似于os.stat() |
Path.mkdir(mode=0o777, parents=False, exist_ok=False) | 创建directory |
Path.rmdir() | 删除directory |
Path.touch(mode=0o666, exist_ok=True) | 在当前路径下创建文件 |
Path.rename(target) | 重命名 |
Path.replace(target) | 重命名,并返回新的path object |
文件读写
方法 | 描述 |
---|---|
Path.open(mode='r', buffering=-1, encoding=None, errors=None, newline=None) | 打开文件 |
Path.read_bytes() | 二进制读取 |
Path.read_text(encoding=None, errors=None) | 文本读取 |
Path.write_bytes(data) | 二进制写入 |
Path.write_text(data, encoding=None, errors=None) | 文本写入 |
其他
Path.chmod(mode)
|更改file mode,类似于os.chmod()
Path.expanduser()
|
Path.group()
|所属组
Path.is_mount()
|
Path.is_symlink()
|
Path.is_socket()
|
Path.is_fifo()
|
Path.is_block_device()
|
Path.is_char_device()
|
Path.lchmod(mode)
|Like Path.chmod()
Path.lstat()
|Path.stat()
Path.owner()
|所有者
Path.rglob(pattern)
|递归调用glob,等于输入了**/
Path.symlink_to
|创建软连接
Path.unlink(missing_ok=False)
|移除链接
Path.link_to(target)
|创建一个硬链接