Python文件操作实战第3篇
Python文件操作实战第3篇。本文详细讲解Python文件读写、目录操作、路径处理等实用技能。Introduction:文件操作是Python编程中最常用的技能之一,无论是配置文件读取、日志处理还是数据持久化,都离不开文件操作。Python内置的open函数简洁强大,配合with语句可以安全地管理文件资源,避免忘记关闭文件导致的资源泄漏。本文涵盖文件读写、JSON/YAML/TOML配置处理、目录遍历、路径拼接、文件备份等实用场景,配完整代码示例,帮助读者掌握Python文件操作的核心方法。
文件基础读写:Python用open函数打开文件,默认是只读模式。用with语句自动关闭文件更安全。示例代码:with open('data.txt', 'r', encoding='utf-8') as f: content = f.read() print(content) 写入文件:with open('output.txt', 'w', encoding='utf-8') as f: f.write('Hello World') 追加模式:with open('log.txt', 'a', encoding='utf-8') as f: f.write('new line\n')
JSON配置文件处理:项目中经常用JSON作为配置文件格式,Python的json模块可以方便读写。import json config = {'host': 'localhost', 'port': 8080, 'debug': True} with open('config.json', 'w', encoding='utf-8') as f: json.dump(config, f, indent=2) 读取配置:with open('config.json', 'r', encoding='utf-8') as f: cfg = json.load(f) print(cfg['host'])
YAML配置处理:有些项目用YAML作为配置格式,需要安装pyyaml库。import yaml with open('config.yaml', 'r', encoding='utf-8') as f: cfg = yaml.safe_load(f) print(cfg['database']['host'])
TOML配置处理:Python3.11+,内置tomllib支持读取TOML文件。import tomllib with open('config.toml', 'rb') as f: cfg = tomllib.load(f) print(cfg['server']['port'])
目录和路径处理:os.path和pathlib是处理路径的两个主要模块。from pathlib import Path base = Path('data') / 'output' base.mkdir(parents=True, exist_ok=True) file_path = base / 'result.txt' file_path.write_text('内容', encoding='utf-8') 相比os.path,pathlib更直观,面向对象设计更合理。
递归遍历目录:import os for root, dirs, files in os.walk('.'): for f in files: if f.endswith('.py'): print(os.path.join(root, f)) 也可以用pathlib:list(Path('.').rglob('*.py'))
文件备份和压缩:实际应用中经常需要对文件做备份。import shutil, zipfile from datetime import datetime src = 'data.txt' backup_dir = Path('backups') backup_dir.mkdir(exist_ok=True) timestamp = datetime.now().strftime('%Y%m%d_%H%M%S') shutil.copy2(src, backup_dir / f'data_{timestamp}.txt') 压缩备份:with zipfile.ZipFile(f'backup_{timestamp}.zip', 'w') as zf: zf.write(src)
以上就是Python文件操作的核心知识点,建议动手实践。