前言
相比常用的 os.path而言,pathlib 对于目录路径的操作更简介也更贴近 Pythonic。但是它不单纯是为了简化操作,还有更大的用途。
pathlib 是Python内置库,Python 文档给它的定义是:The pathlib module – object-oriented filesystem paths(面向对象的文件系统路径)。pathlib 提供表示文件系统路径的类,其语义适用于不同的操作系统。
更多详细的内容可以参考官方文档:https://docs.python.org/3/library/pathlib.html#methods
1. pathlib模块下Path类的基本使用
from pathlib import Path path = r'D:\python\pycharm2020\program\pathlib模块的基本使用.py' p = Path(path) print(p.name) # 获取文件名 print(p.stem) # 获取文件名除后缀的部分 print(p.suffix) # 获取文件后缀 print(p.parent) # 相当于dirname print(p.parent.parent.parent) print(p.parents) # 返回一个iterable 包含所有父目录 for i in p.parents: print(i) print(p.parts) # 将路径通过分隔符分割成一个元组
运行结果如下:
pathlib模块的基本使用.py
pathlib模块的基本使用
.py
D:\python\pycharm2020\program
D:\python
<WindowsPath.parents>
D:\python\pycharm2020\program
D:\python\pycharm2020
D:\python
D:\
('D:\\', 'python', 'pycharm2020', 'program', 'pathlib模块的基本使用.py')
- Path.cwd():Return a new path object representing the current directory
- Path.home():Return a new path object representing the user's home directory
- Path.expanduser():Return a new path with expanded ~ and ~user constructs
from pathlib import Path path_1 = Path.cwd() # 获取当前文件路径 path_2 = Path.home() p1 = Path('~/pathlib模块的基本使用.py') print(path_1) print(path_2) print(p1.expanduser())
运行结果如下:
D:\python\pycharm2020\program
C:\Users\Administrator
C:\Users\Administrator\pathlib模块的基本使用.py
Path.stat():Return a os.stat_result object containing information about this path
from pathlib import Path import datetime p = Path('pathlib模块的基本使用.py') print(p.stat()) # 获取文件详细信息 print(p.stat().st_size) # 文件的字节大小 print(p.stat().st_ctime) # 文件创建时间 print(p.stat().st_mtime) # 上次修改文件的时间 creat_time = datetime.datetime.fromtimestamp(p.stat().st_ctime) st_mtime = datetime.datetime.fromtimestamp(p.stat().st_mtime) print(f'该文件创建时间:{creat_time}') print(f'上次修改该文件的时间:{st_mtime}')
运行结果如下:
os.stat_result(st_mode=33206, st_ino=3659174698076635, st_dev=3730828260, st_nlink=1, st_uid=0, st_gid=0, st_size=543, st_atime=1597366826, st_mtime=1597366826, st_ctime=1597320585)
543
1597320585.7657475
1597366826.9711637
该文件创建时间:2020-08-13 20:09:45.765748
上次修改该文件的时间:2020-08-14 09:00:26.971164
从不同.stat().st_属性 返回的时间戳表示自1970年1月1日以来的秒数,可以用datetime.fromtimestamp将时间戳转换为有用的时间格式。
Path.exists():Whether the path points to an existing file or directory
Path.resolve(strict=False):Make the path absolute,resolving any symlinks. A new path object is returned
from pathlib import Path p1 = Path('pathlib模块的基本使用.py') # 文件 p2 = Path(r'D:\python\pycharm2020\program') # 文件夹 absolute_path = p1.resolve() print(absolute_path) print(Path('.').exists()) print(p1.exists(), p2.exists()) print(p1.is_file(), p2.is_file()) print(p1.is_dir(), p2.is_dir()) print(Path('/python').exists()) print(Path('non_existent_file').exists())
运行结果如下:
D:\python\pycharm2020\program\pathlib模块的基本使用.py
True
True True
True False
False True
True
False
Path.iterdir():When the path points to a directory,yield path objects of the directory contents
from pathlib import Path p = Path('/python') for child in p.iterdir(): print(child)
运行结果如下:
\python\Anaconda
\python\EVCapture
\python\Evernote_6.21.3.2048.exe
\python\Notepad++
\python\pycharm-community-2020.1.3.exe
\python\pycharm2020
\python\pyecharts-assets-master
\python\pyecharts-gallery-master
\python\Sublime text 3
Path.glob(pattern):Glob the given relative pattern in the directory represented by this path, yielding all matching files (of any kind),The “**” pattern means “this directory and all subdirectories, recursively”. In other words, it enables recursive globbing.
Note:Using the “**” pattern in large directory trees may consume an inordinate amount of time
递归遍历该目录下所有文件,获取所有符合pattern的文件,返回一个generator。
获取该文件目录下所有.py文件
from pathlib import Path path = r'D:\python\pycharm2020\program' p = Path(path) file_name = p.glob('**/*.py') print(type(file_name)) # <class 'generator'> for i in file_name: print(i)
获取该文件目录下所有.jpg图片
from pathlib import Path path = r'D:\python\pycharm2020\program' p = Path(path) file_name = p.glob('**/*.jpg') print(type(file_name)) # <class 'generator'> for i in file_name: print(i)
获取给定目录下所有.txt文件、.jpg图片和.py文件
from pathlib import Path def get_files(patterns, path): all_files = [] p = Path(path) for item in patterns: file_name = p.rglob(f'**/*{item}') all_files.extend(file_name) return all_files path = input('>请输入文件路径:') results = get_files(['.txt', '.jpg', '.py'], path) print(results) for file in results: print(file)
Path.mkdir(mode=0o777, parents=False, exist_ok=False)
- Create a new directory at this given path. If mode is given, it is combined with the process' umask value to determine the file mode and access flags. If the path already exists, FileExistsError is raised.
- If parents is true, any missing parents of this path are created as needed; they are created with the default permissions without taking mode into account (mimicking the POSIX mkdir -p command).
- If parents is false (the default), a missing parent raises FileNotFoundError.
- If exist_ok is false (the default), FileExistsError is raised if the target directory already exists.
- If exist_ok is true, FileExistsError exceptions will be ignored (same behavior as the POSIX mkdir -p command), but only if the last path component is not an existing non-directory file.
Changed in version 3.5: The exist_ok parameter was added.
Path.rmdir():Remove this directory. The directory must be empty.
from pathlib import Path p = Path(r'D:\python\pycharm2020\program\test') p.mkdir() p.rmdir()
from pathlib import Path p = Path(r'D:\python\test1\test2\test3') p.mkdir(parents=True) # If parents is true, any missing parents of this path are created as needed p.rmdir() # 删除的是test3文件夹
from pathlib import Path p = Path(r'D:\python\test1\test2\test3') p.mkdir(exist_ok=True)
- Path.unlink(missing_ok=False):Remove this file or symbolic link. If the path points to a directory, use Path.rmdir() instead. If missing_ok is false (the default), FileNotFoundError is raised if the path does not exist. If missing_ok is true, FileNotFoundError exceptions will be ignored. Changed in version 3.8:The missing_ok parameter was added.
- Path.rename(target):Rename this file or directory to the given target, and return a new Path instance pointing to target. On Unix, if target exists and is a file, it will be replaced silently if the user has permission. target can be either a string or another path object.
- Path.open(mode=‘r', buffering=-1, encoding=None, errors=None, newline=None):Open the file pointed to by the path, like the built-in open() function does.
from pathlib import Path p = Path('foo.txt') p.open(mode='w').write('some text') target = Path('new_foo.txt') p.rename(target) content = target.open(mode='r').read() print(content) target.unlink()
2. 与os模块用法的对比
总结
《魔兽世界》大逃杀!60人新游玩模式《强袭风暴》3月21日上线
暴雪近日发布了《魔兽世界》10.2.6 更新内容,新游玩模式《强袭风暴》即将于3月21 日在亚服上线,届时玩家将前往阿拉希高地展开一场 60 人大逃杀对战。
艾泽拉斯的冒险者已经征服了艾泽拉斯的大地及遥远的彼岸。他们在对抗世界上最致命的敌人时展现出过人的手腕,并且成功阻止终结宇宙等级的威胁。当他们在为即将于《魔兽世界》资料片《地心之战》中来袭的萨拉塔斯势力做战斗准备时,他们还需要在熟悉的阿拉希高地面对一个全新的敌人──那就是彼此。在《巨龙崛起》10.2.6 更新的《强袭风暴》中,玩家将会进入一个全新的海盗主题大逃杀式限时活动,其中包含极高的风险和史诗级的奖励。
《强袭风暴》不是普通的战场,作为一个独立于主游戏之外的活动,玩家可以用大逃杀的风格来体验《魔兽世界》,不分职业、不分装备(除了你在赛局中捡到的),光是技巧和战略的强弱之分就能决定出谁才是能坚持到最后的赢家。本次活动将会开放单人和双人模式,玩家在加入海盗主题的预赛大厅区域前,可以从强袭风暴角色画面新增好友。游玩游戏将可以累计名望轨迹,《巨龙崛起》和《魔兽世界:巫妖王之怒 经典版》的玩家都可以获得奖励。
更新日志
- 【雨果唱片】中国管弦乐《鹿回头》WAV
- APM亚流新世代《一起冒险》[FLAC/分轨][106.77MB]
- 崔健《飞狗》律冻文化[WAV+CUE][1.1G]
- 罗志祥《舞状元 (Explicit)》[320K/MP3][66.77MB]
- 尤雅.1997-幽雅精粹2CD【南方】【WAV+CUE】
- 张惠妹.2007-STAR(引进版)【EMI百代】【WAV+CUE】
- 群星.2008-LOVE情歌集VOL.8【正东】【WAV+CUE】
- 罗志祥《舞状元 (Explicit)》[FLAC/分轨][360.76MB]
- Tank《我不伟大,至少我能改变我。》[320K/MP3][160.41MB]
- Tank《我不伟大,至少我能改变我。》[FLAC/分轨][236.89MB]
- CD圣经推荐-夏韶声《谙2》SACD-ISO
- 钟镇涛-《百分百钟镇涛》首批限量版SACD-ISO
- 群星《继续微笑致敬许冠杰》[低速原抓WAV+CUE]
- 潘秀琼.2003-国语难忘金曲珍藏集【皇星全音】【WAV+CUE】
- 林东松.1997-2039玫瑰事件【宝丽金】【WAV+CUE】