python Pathlib学习笔记

Pathlib

PathlibPathPurePath 两个常用的模块。Path 是带有 IO 操作的对象,可以使用 Path.exists()Path.is_file() 等方法。而 PurePath 可以简单理解为字符串,不能进行 IO 的操作。如果你只是单纯的进行路径字符拼接、路径分割等,可以使用 PurePath。否则你可能想要用的是 Path

Path(带IO)

基础使用:

>>> from pathlib import Path
>>> p = Path('.')

iterdir() : 遍历

>>> [x for x in p.iterdir()]
[PosixPath('.hg'), PosixPath('docs'), PosixPath('dist'),
 PosixPath('__pycache__'), PosixPath('build')]

glob :路径匹配查找,"**" 模式表示 “此目录以及所有子目录,递归”

>>> list(p.glob('**/*.py'))
[PosixPath('test_pathlib.py'), PosixPath('setup.py'),
 PosixPath('pathlib.py'), PosixPath('docs/conf.py'),
 PosixPath('build/lib/pathlib.py')]

rglob() : 递归查找,这就像调用 Path.glob时在给定的相对 pattern 前面添加了"``**/()"

>>> sorted(Path().rglob("*.py"))
[PosixPath('build/lib/pathlib.py'),
 PosixPath('docs/conf.py'),
 PosixPath('pathlib.py'),
 PosixPath('setup.py'),
 PosixPath('test_pathlib.py')]

路径拼接:

>>> p = Path('/etc')
>>> q = p / 'init.d' / 'reboot'  # 直接使用 / 就能拼接
>>> q
PosixPath('/etc/init.d/reboot')  # 在linux上运行,就是 PosixPath

>>> Path('aaa',"bbb")
WindowsPath('aaa/bbb')  # 在windows上运行,是windowsPath,会自动转换

>>> Path(Path("a"),Path("b"))  # Path也能拼接
WindowsPath('a/b')

parts : 路径分割:

>>> p = Path('c:/Program Files/PSF')
>>> p.parts
('c:\', 'Program Files', 'PSF')

replace : 文件替换:很危险的操作

>>> p
WindowsPath('a.txt')
>>> c
WindowsPath('test.js')

>>> c.replace(p)  # 会将c的文件名重命名为p的文件名,并替换掉p;也就是说p文件被替换掉了
WindowsPath('a.txt')

>>> p.exists()  # p 虽然依然存在,但是内容已经被替换成 c 文件了
True

>>> c.exists()  # c 文件已经不存在了,因为已经重命名为 p 文件
False

resolve() : 绝对路径

>>> q.resolve()
PosixPath('/etc/rc.d/init.d/halt')

cwd() : 当前路径

>>> p.cwd()
WindowsPath('C:/debug_workplace')

home() : 当前用户的家目录:

>>> p.home()
WindowsPath('C:/Users/dca')

stat() : 可以查看路径的访问时间,修改时间等信息

>>> p = Path('setup.py')
>>> p.stat().st_size
956
>>> p.stat().st_mtime
1327883547.852554

chomd() : 改变路径权限

>>> p = Path('setup.py')
>>> p.stat().st_mode
33277
>>> p.chmod(0o444)
>>> p.stat().st_mode
33060

mkdri() : 创建目录

>>> p
WindowsPath('a/b')
>>> p.mkdir(parents=True, exist_ok=True) # 如果没有父目录,则创建父目录,整个路径已经存在也没有关系

rmdir() : 删除目录,必须是空文件夹

>>> p = Path('a/c')
>>> p.rmdir()  # 此时只会删除 c 文件夹, a 依然存在

创建文件:Path.touch(mode=0o666, exist_ok=True)

>>> p = Path('aa.txt')
>>> p.touch()  # 如果文件已经存在,则会修改文件的修改时间为当前时间,不会修改或删除文件内容

删除文件:Path.unlink(missing_ok=False)

>>> p.unlink()
>>> p.exists()
False

路径类型:

>>> q.exists()
True
>>> q.is_dir()
False
>>> q.is_file()
True

打开文件:

>>> with q.open() as f: f.readline()
...
'#!/bin/bash
'

读写二进制:

>>> p = Path('my_binary_file')
>>> p.write_bytes(b'Binary file contents')
20
>>> p.read_bytes()
b'Binary file contents'

读写字符串:

>>> p = Path('my_text_file')
>>> p.write_text('Text file contents')
18
>>> p.read_text()
'Text file contents'

rename(target) : 重命名

>>> p
WindowsPath('a/b')

>>> p.mkdir(parents=True)

>>> c = p.rename(Path('a/c'))  # 注意 rename(PathObj)

>>> p
WindowsPath('a/b')  # 虽然磁盘上 a/b 已经重命名为 a/c,但是 p 的值依然是 a/b
>>> c
WindowsPath('a/c')  # c 才是现在磁盘上真正的文件夹名称

转换成字符串:

>>> str(q)

PurePath(不带IO)

基础使用:

>>> from pathlib import PurePath
>>> PurePath('setup.py')      # Running on a Unix machine
PurePosixPath('setup.py')

路径拼接:

>>> PurePath('foo', 'some/path', 'bar')  # 字符串
PurePosixPath('foo/some/path/bar')

>>> PurePath("a") / 'b' / 'c'  # 也可以直接 / 拼接
PureWindowsPath('a/b/c')

>>> PurePath(Path('foo'), Path('bar'))  # Path对象
PurePosixPath('foo/bar')

# 给出多个绝对路径,以最后一个绝对路径为准 ========
>>> PurePath('/etc', '/usr', 'lib64')
PurePosixPath('/usr/lib64')

>>> PureWindowsPath('c:/Windows', 'd:bar')
PureWindowsPath('d:bar')

# windows下,虽然两个都是绝对路径,但是盘符并不会变
>>> PureWindowsPath('c:/Windows', '/Program Files')
PureWindowsPath('c:/Program Files')

路径分割:

>>> p = PureWindowsPath('c:/Program Files/PSF')
>>> p.parts
('c:\', 'Program Files', 'PSF')

Path,PurePath通用方法

父目录:

>>> p = Path("a/b/c/d")

>>> p.parent
WindowsPath('a/b/c')

>>> list(p.parents)
[WindowsPath('a/b/c'), WindowsPath('a/b'), WindowsPath('a'), WindowsPath('.')]

末尾目录:

>>> PurePosixPath('my/library/setup.py').name
'setup.py'

磁盘符:

>>> p = Path("c:debug")
>>> p.drive
'c:'

后缀:

>>> PurePosixPath('my/library/setup.py').suffix
'.py'
>>> PurePosixPath('my/library.tar.gz').suffix
'.gz'
>>> PurePosixPath('my/library').suffix
''

后缀们:

>>> PurePosixPath('my/library.tar.gar').suffixes
['.tar', '.gar']
>>> PurePosixPath('my/library.tar.gz').suffixes
['.tar', '.gz']
>>> PurePosixPath('my/library').suffixes
[]

去除后缀的主干:

>>> PurePosixPath('my/library.tar.gz').stem
'library.tar'
>>> PurePosixPath('my/library.tar').stem
'library'
>>> PurePosixPath('my/library').stem
'library'

将路径的 转换成 /:

>>> p = PureWindowsPath('c:\windows')
>>> str(p)
'c:\windows'
>>> p.as_posix()
'c:/windows'

是否绝对路径:

>>> PurePosixPath('/a/b').is_absolute()
True

路径拼接:

>>> PurePosixPath('/etc').joinpath('passwd')
PurePosixPath('/etc/passwd')
>>> PurePosixPath('/etc').joinpath(PurePosixPath('passwd'))
PurePosixPath('/etc/passwd')
>>> PurePosixPath('/etc').joinpath('init.d', 'apache2')
PurePosixPath('/etc/init.d/apache2')
>>> PureWindowsPath('c:').joinpath('/Program Files')
PureWindowsPath('c:/Program Files')

路径匹配:

>>> PurePath('a/b.py').match('*.py')
True
>>> PurePath('/a/b/c.py').match('b/*.py')
True
>>> PurePath('/a/b/c.py').match('a/*.py')
False

附录:os 和 pathlib 功能对照

os 和 os.path pathlib
os.path.abspath() Path.resolve()
os.chmod() Path.chmod()
os.mkdir() Path.mkdir()
os.makedirs() 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()Path.home()
os.listdir() Path.iterdir()
os.path.isdir() Path.is_dir()
os.path.isfile() Path.is_file()
os.path.islink() Path.is_symlink()
os.link() Path.link_to()
os.symlink() Path.symlink_to()
os.readlink() Path.readlink()
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
原文地址:https://www.cnblogs.com/wztshine/p/15042937.html