目录
-
-
- 一、背景与核心价值
- 二、路径处理核心库对比
-
- 2.1 常用库功能矩阵
- 2.2 Pathlib面向对象示例
- 三、文件操作四大核心场景
-
- 3.1 创建与写入
- 3.2 读取与解析
- 3.3 修改与更新
- 3.4 删除与清理
- 四、目录操作高阶技巧
-
- 4.1 递归遍历(三种方式)
- 4.2 批量重命名实战
- 4.3 目录差异对比
- 五、综合实战案例
-
- 六、最佳实践总结
-
- 1. 路径处理规范:
- 2. 异常处理模板:
- 3. 性能优化建议:
- Python相关文章(推荐)
一、背景与核心价值
加粗样式文件操作是Python开发中的基础能力,据2023年PyPI统计,超过92%的Python项目涉及文件系统交互。本文将通过20+实战案例,详解以下核心场景需求:
- 自动化运维:批量处理日志文件
- 数据清洗:结构化文件存储
- 应用配置:动态读取配置文件
- 资源管理:监控目录空间变化
二、路径处理核心库对比
2.1 常用库功能矩阵
功能 |
os模块 |
pathlib(推荐) |
shutil |
路径拼接 |
os.path.join |
/ 运算符 |
- |
文件存在性检查 |
os.path.exists |
Path.exists() |
- |
递归删除 |
- |
- |
shutil.rmtree |
元数据获取 |
os.stat |
Path.stat() |
- |
2.2 Pathlib面向对象示例
from pathlib import Path
current_dir = Path.cwd()
config_path = current_dir / "config" / "app.yaml"
print(f"文件后缀: {config_path.suffix}")
print(f"父目录: {config_path.parent}")
三、文件操作四大核心场景
3.1 创建与写入
output = Path("reports/2023/sales.csv")
output.parent.mkdir(parents=True, exist_ok=True)
with output.open("w") as f:
f.write("月份,销售额\n")
f.writelines(["1月,100000\n", "2月,150000\n"])
3.2 读取与解析
with open("server.log", "r", encoding="utf-8") as f:
error_lines = [line.strip() for line in f if "ERROR" in line]
import json
config = json.loads(Path("config.json").read_text())
3.3 修改与更新
from tempfile import NamedTemporaryFile
with open("index.html") as src, NamedTemporaryFile("w", delete=False) as dst:
for line in src:
dst.write(line.replace("旧标题", "新标题"))
Path(dst.name).replace("index.html")
3.4 删除与清理
from send2trash import send2trash
temp_file = Path("temp.data")
temp_file.touch()
send2trash(temp_file)
四、目录操作高阶技巧
4.1 递归遍历(三种方式)
for root, dirs, files in os.walk("project"):
print(f"目录:{root} 包含 {len(files)} 个文件")
py_files = list(Path("src").rglob("*.py"))
with os.scandir("logs") as entries:
for entry in entries:
if entry.is_file() and entry.name.endswith(".log"):
print(f"日志文件: {entry.path}")
4.2 批量重命名实战
for i, img_path in enumerate(Path("photos").glob("*.jpg")):
new_name = f"vacation_{i+1:03d}.jpg"
img_path.rename(img_path.with_name(new_name))
"""
执行前:
photos/
├── IMG_001.jpg
└── IMG_002.jpg
执行后:
photos/
├── vacation_001.jpg
└── vacation_002.jpg
"""
4.3 目录差异对比
from filecmp import dircmp
def print_diff(dcmp):
for name in dcmp.diff_files:
print(f"差异文件: {name}")
for sub_dcmp in dcmp.subdirs.values():
print_diff(sub_dcmp)
dcmp = dircmp("dir1", "dir2")
print_diff(dcmp)
五、综合实战案例
5.1 清理空目录工具
def clean_empty_dirs(root: Path):
for dir in root.rglob("*"):
if dir.is_dir() and not any(dir.iterdir()):
print(f"删除空目录: {dir}")
dir.rmdir()
clean_empty_dirs(Path("tmp_data"))
5.2 文件同步监控
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
class SyncHandler(FileSystemEventHandler):
def on_modified(self, event):
src = Path(event.src_path)
dest = sync_dir / src.relative_to(source_dir)
if src.is_file():
shutil.copy2(src, dest)
print(f"同步文件: {src.name}")
observer = Observer()
observer.schedule(SyncHandler(), "documents", recursive=True)
observer.start()
六、最佳实践总结
1. 路径处理规范:
open("data\reports\2023.csv")
Path("data") / "reports" / "2023.csv"
2. 异常处理模板:
try:
with open("data.csv") as f:
process(f)
except FileNotFoundError as e:
print(f"文件缺失: {e}")
except PermissionError:
print("权限不足")
3. 性能优化建议:
def big_dir_scan(path: Path):
with os.scandir(path) as it:
yield from (entry.path for entry in it)
from multiprocessing import Pool
with Pool(4) as p:
p.map(process_file, Path("data").rglob("*.csv"))
读取
写入
监控
遍历
同步
清理
文件操作
操作类型
open/read
open/write
watchdog
目录操作
os.walk/rglob
shutil.copytree
rmdir
Python相关文章(推荐)
|
|
Python全方位指南 |
Python(1)Python全方位指南:定义、应用与零基础入门实战 |
Python基础数据类型详解 |
Python(2)Python基础数据类型详解:从底层原理到实战应用 |
Python循环 |
Python(3)掌握Python循环:从基础到实战的完整指南 |
Python列表推导式 |
Python(3.1)Python列表推导式深度解析:从基础到工程级的最佳实践 |
Python生成器 |
Python(3.2)Python生成器深度全景解读:从yield底层原理到万亿级数据处理工程实践 |
Python函数编程性能优化 |
Python(4)Python函数编程性能优化全指南:从基础语法到并发调优 |
Python数据清洗 |
Python(5)Python数据清洗指南:无效数据处理与实战案例解析(附完整代码) |
Python邮件自动化 |
Python(6)Python邮件自动化终极指南:从零搭建企业级邮件系统(附完整源码) |
Python通配符基础 |
Python(7)Python通配符完全指南:从基础到高阶模式匹配实战(附场景化代码) |
Python通配符高阶 |
Python(7 升级)Python通配符高阶实战:从模式匹配到百万级文件处理优化(附完整解决方案) |
Python操作系统接口 |
Python(8)Python操作系统接口完全指南:os模块核心功能与实战案例解析 |
Python代码计算全方位指南 |
Python(9)Python代码计算全方位指南:从数学运算到性能优化的10大实战技巧 |
Python数据类型 |
Python(10)Python数据类型完全解析:从入门到实战应用 |
Python判断语句 |
Python(11)Python判断语句全面解析:从基础到高级模式匹配 |
Python参数传递 |
Python(12)深入解析Python参数传递:从底层机制到高级应用实践 |
Python面向对象编程 |
Python(13)Python面向对象编程入门指南:从新手到类与对象(那个她)的华丽蜕变 |
Python内置函数 |
Python(14)Python内置函数完全指南:从基础使用到高阶技巧 |
Python参数传递与拷贝机制 |
Python(15)Python参数传递与拷贝机制完全解析:从值传递到深拷贝实战 |
Python文件操作 |
Python(16)Python文件操作终极指南:安全读写与高效处理实践 |
Python字符编码 |
Python(17)Python字符编码完全指南:从存储原理到乱码终结实战 |
Python中JSON的妙用 |
Python(18)Python中JSON的妙用:详解序列化与反序列化原理及实战案例 |