python 04-标准库:pathlib模块
pathlib模块
-
pathlib模块:是面向对象的文件系统路径操作库,提供接口来处理文件路径。Path是主类
-
Path:Path对象表示文件或目录的路径,Path类会自动选择PosixPath或WindowsPath,具体取决于我们的操作系统
😄 win系统创建path对象
from pathlib import Path
# 创建一个指向当前目录的Path对象
current_path = Path('.')
print(current_path.absolute())
path = Path()
print(path.absolute())# 输出d:\py_related\HelloWorld
current_path1 = Path("D:\\py_related\\test")
print(current_path1)
# 在windows中绝对路径还可以这么写:
current_path2 = Path(r"D:\py_related\test")
print(current_path2)
问:在Python的pathlib模块中,Path()和Path('.')的区别?
答:
- Path():Path()表示当前工作目录的Path对象或一个空的Path对象。取决于具体的Python版本和解释器行为,常为后者。
- Path('.'):Path对象表示当前目录。这里的.是一个特殊的目录名,代表“当前目录”。
- 总之,Path('.')是获取当前工作目录的明确和推荐的方式,如果你想要一个表示当前工作目录的Path对象,请使用Path('.')或Path.cwd()。
- 从上面代码来看我的python版本3.12.5 ,其Path()和Path('.')都表示当前工作目录
😄使用除法操作连接目录和文件名:
from pathlib import Path
# 创建Path对象表示目录
# 只是创建了路径对象,并没有真的在文件系统中创建这个目录
parent_dir = Path(r"D:\py_related\test\new_directory")
# 创建Path对象表示文件名
file_name = Path("example.txt")
# 使用除法操作连接目录和文件名
full_path = parent_dir / file_name
# 输出完整的路径
print(full_path)
😄home() exists() is_file() is_dir()
from pathlib import Path
# 返回当前用户的home目录
print(Path.home()) # C:\Users\zdn
# new_directory这个目录不存在还没有创建
path = Path(r"D:\py_related\test\new_directory")
print(path.exists()) # False
print(path.is_file()) # False
print(path.is_dir()) # False 因为目录不存在所以这里的结果也是假
# D:\py_related\test这个目录是存在的
path2 = Path(r"D:\py_related\test")
print(path2.exists()) # True
print(path2.is_file()) # False
print(path2.is_dir()) # True
😄name stem suffix parent属性 .absolute()方法 with_suffix(),with_stem(),with_name()
from pathlib import Path
# 这个路径不存在 现编的
path = Path(r"ecommerce\test.py")
print(path.exists()) # False
print(path.name) # test.py
print(path.stem) # test
print(path.suffix) # .py
print(path.parent) # ecommerce
path = path.with_name("file.txt")
print(path) # ecommerce\file.txt
print(path.absolute()) # absolute()获取path对象的绝对路径,并不一定真的存在
# d:\py_related\HelloWorld\ecommerce\file.txt
path = path.with_suffix(".py")
print(path) # ecommerce\file.py
path = path.with_stem("exam")
print(path) # ecommerce\exam.py
😄rename()
from pathlib import Path
# 这个路径真实存在
path = Path(r"D:\py_related\test")
# rename()方法必须是存在的路径,实际上也会重新命名;如路径不存在会报错FileNotFoundError
path.rename(r"D:\py_related\test2")
print(path) # 输出D:\py_related\test path仍然是test而不是test2???
😄iterdir()
from pathlib import Path
# 这个路径真实存在
path = Path(r"D:\j\javaPro\test_crawler")
# path.iterdir()使得path对象变为一个生成器对象
print(path.iterdir())
for p in path.iterdir():
print(p)
# 如果数据量不多的话,也可使用list推导式
list_p = [p for p in path.iterdir()]
print(list_p)
😄glob() rglob()
from pathlib import Path
path = Path(r"D:\j\javaPro\test_crawler")
# Path.glob()方法:非递归地遍历指定的目录,并返回所有匹配给定模式的Path对象列表
list_g = [p for p in path.glob("*.*")]
print(list_g)
# rglob():递归地遍历指定的目录,包括子目录
list_r = [p for p in path.rglob("*.class")]
print(list_r)
😄 unlink() stat()
from pathlib import Path
path = Path(r"D:\py_related\test2\test.txt")
path.exists() # True
path.unlink() # 删除了test.txt
path.stat() # 获取文件状态 FileNotFoundError
😄 文件复制、压缩文件
shutil模块是一个提供了一系列对文件和文件集合进行高级操作的函数的模块。它是Python标准库的一部分,因此不需要安装任何额外的第三方包即可使用。
from pathlib import Path
import shutil
source = Path(r"D:\py_related\test2\test.txt")
target = Path(r"D:\py_related\test2\exam.txt")
shutil.copy(source, target)
ZipFile类是一个用于读取和写入ZIP文件的工具
from pathlib import Path
from zipfile import ZipFile
# 创建一个D:\py_related\test2目录下的名为files.zip的压缩文件
# 还可以这么写:zip_file=ZipFile(r"D:\py_related\test2\files.zip","w")
with ZipFile(r"D:\py_related\test2\files.zip", "w") as zip_file:
for p in Path(r"D:\j\javaPro\test_crawler").rglob("*.*"):
zip_file.write(p) #把这个目录下的所有文件压缩到zip_file中
# 使用with as 语句后就不用写zip_file.close()了
with ZipFile(r"D:\py_related\test2\files.zip") as zip:
print(zip.namelist()) # 打印出包含的所有文件目录
info = zip.getinfo('j/javaPro/test_crawler/pom.xml')
# 查看压缩前后的文件大小 均为1653因为这个文件比较小,故没有压缩处理
print(info.file_size, info.compress_size)
zip.extractall(r"D:\py_related\test2\unzip")
解压成功如下:
😄 输出path路径对应的文件的创建时间
(这是chatGPT给出的方案,但是在VScode中提示st_ctime已经不再推荐使用)
from pathlib import Path
import time
path = Path(r"D:\py_related\test2\test.txt")
# Get the file's status information
file_stat = path.stat()
# Access the creation time (on Unix, this may not be available)
# On Windows, this is creation time; on Unix, it's changed time
creation_time = file_stat.st_ctime
# Convert the creation time to a human-readable format
readable_time = time.ctime(creation_time)
print(f"Creation time for '{path}': {readable_time}")
# 输出:Creation time for 'D:\py_related\test2\test.txt': Thu Aug 22 16:12:48 2024
分类:
研_需 / python
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异