一、文件操作基础
1.open()函数核心语法
file = open("filename.txt", mode="r", encoding="utf-8")
- 参数说明:filename:文件路径(支持相对/绝对路径)。mode:文件打开模式(默认"r",即只读)。r:读取(默认)。w:写入(覆盖原有内容)。a:追加(在文件末尾添加内容)。x:创建新文件(若存在则报错)。b:二进制模式(如"rb"读二进制,"wb"写二进制)。+:读写模式(如"r+"可读可写)。encoding:文本文件的编码格式(如utf-8、gbk,默认依赖系统)。
2. 读取文件内容
# 读取全部内容
with open("file.txt", "r", encoding="utf-8") as f:
content = f.read()
print(content)
# 逐行读取
with open("file.txt", "r") as f:
for line in f:
print(line.strip()) # 去除首尾空白
# 读取所有行(返回列表)
with open("file.txt") as f:
lines = f.readlines()
print(lines) # ['line1\n', 'line2\n', ...]
3. 写入文件内容
# 覆盖写入(模式"w")
with open("output.txt", "w", encoding="utf-8") as f:
f.write("Hello, Python!\n")
f.write("这是第二行。")
# 追加写入(模式"a")
with open("log.txt", "a") as f:
f.write("2025-07-18: 新增日志\n")
二、文件操作进阶
1. 文件指针操作
- seek(offset, whence):移动文件指针到指定位置。offset:偏移量(字节)。whence:基准位置(默认0表示文件开头,1表示当前位置,2表示文件末尾)。
- tell():获取当前文件指针位置。
with open("file.txt", "r+") as f:
print(f.read(5)) # 读取前5个字符
print(f.tell()) # 输出:5
f.seek(0) # 移动到文件开头
print(f.readline()) # 重新读取第一行
2. 二进制文件操作
# 写入二进制文件(如图片)
with open("image.jpg", "rb") as f:
data = f.read()
# 读取二进制文件
with open("image.jpg", "wb") as f:
f.write(data)
3. 上下文管理器(with语句)
自动管理文件资源,无需手动调用close():
with open("file.txt") as f:
content = f.read()
# 文件已自动关闭
三、异常处理与最佳实践
1. 异常处理
try:
with open("file.txt") as f:
data = f.read()
except FileNotFoundError:
print("文件不存在!")
except PermissionError:
print("无文件访问权限!")
except Exception as e:
print(f"未知错误:{e}")
2. 最佳实践
- 明确文件模式:始终指定mode(如"r"、"w")。
- 指定编码:处理文本文件时显式声明编码(如encoding="utf-8")。
- 使用with语句:避免资源泄漏。
- 谨慎覆盖文件:写入前备份或使用临时文件。
四、实战案例
案例1:统计文本文件行数
count = 0
with open("data.txt", "r") as f:
for line in f:
count += 1
print(f"文件共有 {count} 行")
案例2:合并多个CSV文件
import os
output_file = "combined.csv"
with open(output_file, "w") as outfile:
for filename in os.listdir("csv_files"):
if filename.endswith(".csv"):
with open(os.path.join("csv_files", filename), "r") as infile:
outfile.write(infile.read())
案例3:日志文件轮转
import time
log_file = "app.log"
max_size = 1024 # 1KB
while True:
with open(log_file, "a") as f:
f.write(f"{time.time()}: 日志内容\n")
f.flush()
# 检查文件大小
if os.path.getsize(log_file) > max_size:
# 备份并重置文件
os.rename(log_file, f"app_{time.time()}.log")
open(log_file, "w").close()
time.sleep(1)
五、总结与下一步
- 核心收获:
- 掌握文件读写基础(open()、read()、write())。
- 理解文件指针操作和二进制文件处理。
- 学会异常处理和资源管理(with语句)。
