本文目录导读:

我来给你介绍几种封装文件操作的Python工具案例,从简单到高级:
基础文件读写封装
import os
import json
import pickle
from typing import Any, Optional, List
class FileOperator:
"""基础文件操作工具类"""
@staticmethod
def read_text(file_path: str, encoding: str = 'utf-8') -> str:
"""读取文本文件"""
try:
with open(file_path, 'r', encoding=encoding) as f:
return f.read()
except FileNotFoundError:
print(f"文件 {file_path} 不存在")
return ""
except Exception as e:
print(f"读取文件失败: {e}")
return ""
@staticmethod
def write_text(file_path: str, content: str, encoding: str = 'utf-8'):
"""写入文本文件"""
try:
# 自动创建目录
os.makedirs(os.path.dirname(file_path), exist_ok=True)
with open(file_path, 'w', encoding=encoding) as f:
f.write(content)
print(f"成功写入文件: {file_path}")
except Exception as e:
print(f"写入文件失败: {e}")
@staticmethod
def append_text(file_path: str, content: str, encoding: str = 'utf-8'):
"""追加文本到文件"""
try:
with open(file_path, 'a', encoding=encoding) as f:
f.write(content)
except Exception as e:
print(f"追加内容失败: {e}")
JSON文件处理封装
class JSONFileHandler:
"""JSON文件处理工具"""
def __init__(self, file_path: str):
self.file_path = file_path
self._data = None
def read(self, default: Any = None) -> Any:
"""读取JSON文件"""
try:
with open(self.file_path, 'r', encoding='utf-8') as f:
self._data = json.load(f)
return self._data
except (FileNotFoundError, json.JSONDecodeError):
return default
def write(self, data: Any, indent: int = 2):
"""写入JSON文件"""
try:
os.makedirs(os.path.dirname(self.file_path), exist_ok=True)
with open(self.file_path, 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False, indent=indent)
self._data = data
except Exception as e:
print(f"JSON写入失败: {e}")
def update(self, key: str, value: Any):
"""更新JSON中的某个键值"""
if self._data is None:
self.read()
if self._data is None:
self._data = {}
self._data[key] = value
self.write(self._data)
def delete_key(self, key: str):
"""删除JSON中的某个键"""
if self._data and key in self._data:
del self._data[key]
self.write(self._data)
配置文件管理器
class ConfigManager:
"""配置文件管理器 - 支持多种格式"""
def __init__(self, config_path: str, config_type: str = 'json'):
self.config_path = config_path
self.config_type = config_type
self.config = {}
self.load()
def load(self):
"""加载配置"""
if self.config_type == 'json':
handler = JSONFileHandler(self.config_path)
self.config = handler.read(default={})
elif self.config_type == 'pickle':
try:
with open(self.config_path, 'rb') as f:
self.config = pickle.load(f)
except:
self.config = {}
def get(self, key: str, default: Any = None) -> Any:
"""获取配置项"""
return self.config.get(key, default)
def set(self, key: str, value: Any):
"""设置配置项"""
self.config[key] = value
self.save()
def save(self):
"""保存配置"""
if self.config_type == 'json':
handler = JSONFileHandler(self.config_path)
handler.write(self.config)
elif self.config_type == 'pickle':
with open(self.config_path, 'wb') as f:
pickle.dump(self.config, f)
CSV文件处理工具
import csv
from typing import List, Dict
class CSVFileHandler:
"""CSV文件处理工具"""
def __init__(self, file_path: str, delimiter: str = ','):
self.file_path = file_path
self.delimiter = delimiter
def read_all(self, has_header: bool = True) -> List[Dict]:
"""读取所有行,返回字典列表"""
data = []
try:
with open(self.file_path, 'r', encoding='utf-8') as f:
reader = csv.DictReader(f, delimiter=self.delimiter) if has_header else csv.reader(f)
for row in reader:
data.append(row)
except FileNotFoundError:
print(f"文件 {self.file_path} 不存在")
return data
def write_rows(self, headers: List[str], rows: List[List]):
"""写入多行数据"""
try:
with open(self.file_path, 'w', newline='', encoding='utf-8') as f:
writer = csv.writer(f, delimiter=self.delimiter)
writer.writerow(headers)
writer.writerows(rows)
except Exception as e:
print(f"写入CSV失败: {e}")
def append_row(self, row: List):
"""追加一行数据"""
try:
with open(self.file_path, 'a', newline='', encoding='utf-8') as f:
writer = csv.writer(f, delimiter=self.delimiter)
writer.writerow(row)
except Exception as e:
print(f"追加CSV失败: {e}")
万能文件管理类
from pathlib import Path
import shutil
class FileManager:
"""万能文件管理器"""
def __init__(self, base_path: str = '.'):
self.base_path = Path(base_path)
self.base_path.mkdir(exist_ok=True)
def create_file(self, filename: str, content: str = '') -> Path:
"""创建文件"""
file_path = self.base_path / filename
file_path.parent.mkdir(parents=True, exist_ok=True)
file_path.write_text(content, encoding='utf-8')
return file_path
def read_file(self, filename: str) -> Optional[str]:
"""读取文件"""
file_path = self.base_path / filename
if file_path.exists():
return file_path.read_text(encoding='utf-8')
return None
def copy_file(self, src: str, dst: str) -> bool:
"""复制文件"""
try:
src_path = self.base_path / src
dst_path = self.base_path / dst
dst_path.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(src_path, dst_path)
return True
except Exception as e:
print(f"复制文件失败: {e}")
return False
def move_file(self, src: str, dst: str) -> bool:
"""移动文件"""
try:
src_path = self.base_path / src
dst_path = self.base_path / dst
dst_path.parent.mkdir(parents=True, exist_ok=True)
shutil.move(str(src_path), str(dst_path))
return True
except Exception as e:
print(f"移动文件失败: {e}")
return False
def delete_file(self, filename: str) -> bool:
"""删除文件"""
try:
file_path = self.base_path / filename
if file_path.exists():
file_path.unlink()
return True
return False
except Exception as e:
print(f"删除文件失败: {e}")
return False
def list_files(self, pattern: str = '*') -> List[Path]:
"""列出文件"""
return list(self.base_path.glob(pattern))
def get_detailed_info(self, filename: str) -> Dict:
"""获取文件详细信息"""
file_path = self.base_path / filename
if not file_path.exists():
return {}
return {
'name': file_path.name,
'size': file_path.stat().st_size,
'created': file_path.stat().st_ctime,
'modified': file_path.stat().st_mtime,
'is_file': file_path.is_file(),
'is_dir': file_path.is_dir(),
'extension': file_path.suffix
}
使用示例
# 示例1:使用文本文件操作
text_operator = FileOperator()
text_operator.write_text('example.txt', 'Hello, World!')
content = text_operator.read_text('example.txt')
print(content)
# 示例2:使用JSON处理器
json_handler = JSONFileHandler('config/settings.json')
json_handler.write({'name': 'Python', 'version': '3.9'})
data = json_handler.read()
print(data)
# 示例3:使用配置管理器
config = ConfigManager('config.json')
config.set('theme', 'dark')
print(config.get('theme'))
# 示例4:使用CSV处理器
csv_handler = CSVFileHandler('data.csv')
csv_handler.write_rows(['name', 'age'], [['Alice', 25], ['Bob', 30]])
all_data = csv_handler.read_all()
print(all_data)
# 示例5:使用文件管理器
fm = FileManager('./my_files')
fm.create_file('notes.txt', 'This is a note')
fm.copy_file('notes.txt', 'backup/notes.txt')
info = fm.get_detailed_info('notes.txt')
print(info)
封装原则
- 单一职责:每个类只负责一种类型的文件操作
- 错误处理:添加适当的异常处理,避免程序崩溃
- 路径安全:自动创建不存在的目录
- 编码处理:统一使用UTF-8编码
- 日志记录:重要的操作记录日志
- 通用性:参数化配置,支持不同场景
这些封装案例可以让你更高效地处理文件操作,避免重复代码,提高代码的可维护性。