lesson15:Python的文件操作
目录
一、文件操作基础:open方法详解
1.1 基本语法与参数
1.2 文件读写的三种方式
1.2.1 文本文件读取
1.2.2 文本文件写入
1.2.3 二进制文件操作(如图片、视频)
1.3 上下文管理器(with语句)的优势
二、文件系统交互:os与os.path模块
2.1 路径处理核心函数
2.2 目录管理操作
2.3 文件属性与权限
三、数据序列化与反序列化:json模块
3.1 核心概念
3.2 基本用法示例
3.2.1 Python对象转JSON(序列化)
3.2.2 JSON转Python对象(反序列化)
3.3 高级:自定义数据类型处理
四、实战案例:文件操作综合应用
案例1:批量处理文本文件
案例2:JSON配置文件读写
五、避坑指南与最佳实践
总结
前言
文件操作是Python编程中不可或缺的基础技能,无论是数据处理、配置管理还是日志记录,都离不开对文件的读写与管理。本文将系统讲解Python文件操作的核心知识,包括open
方法的使用、os
模块的文件系统交互,以及json
模块的数据序列化与反序列化技巧,帮助你轻松掌握文件操作的方方面面。
一、文件操作基础:open
方法详解
open
函数是Python操作文件的入口,它负责创建文件对象(file object),并提供对文件的读写接口。掌握其参数与用法是文件操作的第一步。
1.1 基本语法与参数
file = open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
核心参数解析:
file
:文件路径(绝对路径或相对路径)mode
:打开模式(决定文件的读写方式),常用值如下:'r'
:只读模式(默认),文件不存在则报错'w'
:写入模式,覆盖原有内容,文件不存在则创建'a'
:追加模式,在文件末尾添加内容,文件不存在则创建'r+'
:读写模式,可同时读写'b'
:二进制模式(如'rb'
、'wb'
),用于非文本文件(图片、音频等)'t'
:文本模式(默认,如'rt'
、'wt'
),用于文本文件
1.2 文件读写的三种方式
1.2.1 文本文件读取
# 读取整个文件
with open('example.txt', 'r', encoding='utf-8') as f:
content = f.read() # 读取全部内容
print(content)# 逐行读取(适合大文件)
with open('example.txt', 'r', encoding='utf-8') as f:
for line in f:
print(line.strip()) # 去除换行符
1.2.2 文本文件写入
# 覆盖写入
with open('output.txt', 'w', encoding='utf-8') as f:
f.write('Hello, Python!\n') # 写入单行
f.writelines(['First line\n', 'Second line\n']) # 写入多行# 追加写入
with open('output.txt', 'a', encoding='utf-8') as f:
f.write('This line is appended.\n')
1.2.3 二进制文件操作(如图片、视频)
# 读取二进制文件
with open('image.jpg', 'rb') as f:
data = f.read() # 字节流数据# 写入二进制文件
with open('copy.jpg', 'wb') as f:
f.write(data) # 复制图片
1.3 上下文管理器(with
语句)的优势
使用with
语句操作文件无需手动调用close()
方法,会自动处理文件关闭,避免因忘记关闭导致的资源泄露,是推荐的最佳实践。
二、文件系统交互:os
与os.path
模块
os
模块提供了与操作系统交互的接口,可用于文件路径处理、目录管理、权限控制等;os.path
则专注于路径字符串的解析与拼接,跨平台兼容性更强。
2.1 路径处理核心函数
import os
from os.path import join, abspath, exists, basename, dirname# 路径拼接(自动处理斜杠,跨平台兼容)
path = join('data', 'files', 'report.txt') # Windows: data\files\report.txt; Linux: data/files/report.txt# 获取绝对路径
abs_path = abspath(path) # 如:/home/user/data/files/report.txt# 判断路径是否存在
is_exist = exists(abs_path) # True/False# 分离文件名与目录
filename = basename(abs_path) # 'report.txt'
dirname = dirname(abs_path) # '/home/user/data/files'
2.2 目录管理操作
# 创建目录(单级)
os.mkdir('new_dir') # 目录已存在会报错# 创建多级目录
os.makedirs('parent/child/grandchild', exist_ok=True) # exist_ok=True避免目录存在时报错# 列出目录内容
files = os.listdir('parent') # 返回文件名列表# 删除文件/目录
os.remove('file.txt') # 删除文件
os.rmdir('empty_dir') # 删除空目录(非空目录需用shutil.rmtree)
2.3 文件属性与权限
# 获取文件大小(字节)
file_size = os.path.getsize('example.txt')# 获取修改时间(时间戳)
modify_time = os.path.getmtime('example.txt')
from datetime import datetime
print(datetime.fromtimestamp(modify_time)) # 转换为可读时间# 修改文件权限(Unix系统)
os.chmod('script.sh', 0o755) # 赋予执行权限
三、数据序列化与反序列化:json
模块
json
(JavaScript Object Notation)是一种轻量级数据交换格式,json
模块提供了Python数据结构与JSON格式之间的转换功能,广泛用于配置文件、API数据传输等场景。
3.1 核心概念
- 序列化(Serialization):将Python对象(如字典、列表)转换为JSON字符串(
dumps
/dump
) - 反序列化(Deserialization):将JSON字符串转换为Python对象(
loads
/load
)
3.2 基本用法示例
3.2.1 Python对象转JSON(序列化)
import jsondata = {
'name': 'Alice',
'age': 30,
'hobbies': ['reading', 'coding'],
'is_student': False,
'address': None
}# 转换为JSON字符串(dumps = dump string)
json_str = json.dumps(data, indent=4, ensure_ascii=False)
print(json_str)
# 输出:
# {
# "name": "Alice",
# "age": 30,
# "hobbies": [
# "reading",
# "coding"
# ],
# "is_student": false,
# "address": null
# }# 直接写入文件(dump)
with open('data.json', 'w', encoding='utf-8') as f:
json.dump(data, f, indent=4, ensure_ascii=False)
常用参数:
indent
:缩进空格数,美化输出ensure_ascii
:False保留非ASCII字符(如中文)sort_keys
:True按字典键排序
3.2.2 JSON转Python对象(反序列化)
# 从JSON字符串解析(loads = load string)
json_str = '{"name": "Bob", "age": 25, "scores": [90.5, 88, 95]}'
data = json.loads(json_str)
print(type(data)) # <class 'dict'>
print(data['scores'][0]) # 90.5# 从文件读取并解析(load)
with open('data.json', 'r', encoding='utf-8') as f:
data = json.load(f)
print(data['hobbies']) # ['reading', 'coding']
3.3 高级:自定义数据类型处理
JSON仅支持有限的数据类型(dict
、list
、str
、int
、float
、bool
、None
),对于datetime
、set
等类型,需自定义编码器和解码器。
from datetime import datetime# 自定义编码器:处理datetime类型
class CustomEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime):
return obj.isoformat() # 转换为ISO格式字符串
return super().default(obj)data = {'event_time': datetime(2023, 10, 1, 14, 30)}
json_str = json.dumps(data, cls=CustomEncoder)
print(json_str) # {"event_time": "2023-10-01T14:30:00"}# 自定义解码器:解析datetime字符串
def custom_decoder(obj):
if 'event_time' in obj:
obj['event_time'] = datetime.fromisoformat(obj['event_time'])
return objdata = json.loads(json_str, object_hook=custom_decoder)
print(type(data['event_time'])) # <class 'datetime.datetime'>
四、实战案例:文件操作综合应用
案例1:批量处理文本文件
需求:读取docs
目录下所有.txt
文件,统计总字符数并生成报告。
import os
from os.path import join, splitextdef count_text_files(directory):
total_chars = 0
report = []
for root, _, files in os.walk(directory):
for file in files:
if splitext(file)[1].lower() == '.txt':
path = join(root, file)
with open(path, 'r', encoding='utf-8', errors='ignore') as f:
content = f.read()
char_count = len(content)
total_chars += char_count
report.append(f"{path}: {char_count} characters")
report.append(f"\nTotal characters across all .txt files: {total_chars}")
return '\n'.join(report)# 执行并保存报告
result = count_text_files('docs')
with open('text_report.txt', 'w', encoding='utf-8') as f:
f.write(result)
案例2:JSON配置文件读写
需求:创建并读取一个包含程序配置的JSON文件。
import json# 保存配置
config = {
'database': {
'host': 'localhost',
'port': 5432,
'timeout': 30
},
'log_level': 'INFO',
'features': ['auto_save', 'cloud_sync']
}with open('config.json', 'w', encoding='utf-8') as f:
json.dump(config, f, indent=4)# 加载配置
with open('config.json', 'r', encoding='utf-8') as f:
loaded_config = json.load(f)print(f"Database host: {loaded_config['database']['host']}")
print(f"Enabled features: {', '.join(loaded_config['features'])}")
五、避坑指南与最佳实践
-
路径处理:始终使用
os.path.join
或Python 3.4+的pathlib
模块拼接路径,避免硬编码斜杠(/
或\
)导致的跨平台问题。 -
编码规范:读写文本文件时显式指定
encoding='utf-8'
,避免因系统默认编码不一致导致的乱码。 -
异常处理:文件操作可能抛出
FileNotFoundError
、PermissionError
等异常,建议使用try-except
捕获:try: with open('sensitive_data.txt', 'r') as f: content = f.read() except FileNotFoundError: print("文件不存在") except PermissionError: print("没有读取权限")
-
大文件处理:读取大文件时避免使用
read()
一次性加载,应采用逐行读取(for line in f
)或分块读取(f.read(1024)
)。 -
JSON注意事项:
- 字典的键必须为字符串类型(JSON规范)
- 不支持
set
、tuple
等类型,需转换为list
后再序列化 - 浮点数序列化可能存在精度问题(如
0.1
在JSON中会转为0.10000000149011612
)
总结
Python的文件操作功能强大且灵活,通过open
方法可以轻松读写各种文件,os
模块实现文件系统的高效管理,json
模块则解决了数据序列化与跨平台交换的问题。掌握这些工具不仅能提升日常开发效率,也是处理数据持久化、配置管理等场景的基础。建议在实践中结合上下文管理器、异常处理等机制,写出更健壮、可维护的代码。
希望本文对你理解Python文件操作有所帮助!如果有任何疑问或补充,欢迎在评论区交流讨论。