上一篇
Python处理TXT文件完全指南 | Python文本操作教程
- Python
- 2025-08-05
- 963
Python处理TXT文件完全指南
在Python编程中,处理文本文件(TXT)是最基础且重要的操作之一。本教程将全面介绍如何使用Python读取、写入和处理TXT文件。
主要内容:
- 打开和关闭TXT文件
- 读取文件的多种方法
- 写入和追加内容
- 处理大型文本文件
- 常见文本处理技巧
- 最佳实践和错误处理
1. 打开和关闭文件
使用内置的open()
函数打开文件,操作完成后使用close()
方法关闭文件。
基本文件操作模式:
'r'
: 读取模式(默认)'w'
: 写入模式(覆盖现有内容)'a'
: 追加模式'r+'
: 读写模式
示例:安全打开文件
# 使用with语句自动管理文件资源
with open('example.txt', 'r', encoding='utf-8') as file:
content = file.read()
print(content)
# 文件会在with块结束后自动关闭
2. 读取文件内容
Python提供多种读取文件内容的方法:
read() - 读取整个文件
with open('file.txt', 'r') as f:
content = f.read()
print(content)
readline() - 逐行读取
with open('file.txt', 'r') as f:
line = f.readline()
while line:
print(line.strip())
line = f.readline()
readlines() - 读取所有行到列表
with open('file.txt', 'r') as f:
lines = f.readlines()
for line in lines:
print(line.strip())
3. 写入和追加内容
写入模式 ('w')
覆盖现有文件或创建新文件
with open('output.txt', 'w') as f:
f.write("第一行内容\n")
f.write("第二行内容\n")
# 注意:这会覆盖文件原有内容
追加模式 ('a')
在文件末尾添加新内容
with open('output.txt', 'a') as f:
f.write("这是追加的内容\n")
f.write("更多追加内容\n")
4. 处理大型文本文件
对于大文件,避免一次性读取全部内容,使用迭代方式逐行处理:
# 高效处理大文件的方法
with open('large_file.txt', 'r', encoding='utf-8') as big_file:
for line_number, line in enumerate(big_file, 1):
# 处理每一行
processed_line = line.strip().upper()
# 每处理10000行输出进度
if line_number % 10000 == 0:
print(f"已处理 {line_number} 行")
# 这里可以添加更多的处理逻辑
5. 常见文本处理技巧
文件内容处理示例
# 读取文件并做各种处理
with open('data.txt', 'r') as file:
# 读取所有行并去除换行符
lines = [line.strip() for line in file.readlines()]
# 过滤空行
non_empty_lines = [line for line in lines if line]
# 统计行数
line_count = len(non_empty_lines)
# 将所有内容转为大写
uppercase_lines = [line.upper() for line in non_empty_lines]
# 查找包含特定关键词的行
keyword = 'error'
error_lines = [line for line in non_empty_lines if keyword in line]
# 将处理结果写入新文件
with open('processed_data.txt', 'w') as output:
output.write(f"文件共 {line_count} 行内容\n")
output.write(f"其中包含关键词 '{keyword}' 的行有 {len(error_lines)} 行\n\n")
output.write("\n".join(uppercase_lines))
6. 最佳实践和错误处理
文件操作最佳实践:
- 始终使用
with
语句确保文件正确关闭 - 明确指定文件编码(推荐UTF-8)
- 处理大文件时使用迭代逐行读取
- 检查文件路径是否存在
- 处理可能的IO异常
错误处理示例:
import os
file_path = 'important_data.txt'
try:
# 检查文件是否存在
if not os.path.exists(file_path):
raise FileNotFoundError(f"文件 {file_path} 不存在")
# 安全打开文件
with open(file_path, 'r', encoding='utf-8') as f:
content = f.read()
# 处理文件内容...
except FileNotFoundError as e:
print(f"错误:{e}")
except IOError as e:
print(f"文件读写错误:{e}")
except Exception as e:
print(f"发生未知错误:{e}")
else:
print("文件处理成功!")
掌握Python文件操作
文本文件处理是Python编程的基础技能,掌握这些技巧将使你能高效处理各种数据任务!
本文由YuZhaiHuo于2025-08-05发表在吾爱品聚,如有疑问,请联系我们。
本文链接:https://521pj.cn/20257383.html
发表评论