Python读写txt文件的多种方法
引言
文本文件(.txt)是最基础、最通用的数据存储格式之一,广泛应用于日志记录、配置文件、数据交换等场景。Python提供了简单易用的内置方法来读写txt文件,无需额外安装库。本文将详细介绍Python中读写txt文件的各种方法,包括基础操作和高级技巧。
1. 写入txt文件
1.1 使用open()和write()方法
这是最基本的写入方法:
# 打开文件进行写入(如果文件不存在会自动创建)
with open('example.txt', 'w', encoding='utf-8') as file:
file.write("这是第一行文本\n")
file.write("这是第二行文本\n")
file.write("这是第三行文本\n")
参数说明:
'w':写入模式(会覆盖已存在的文件)encoding='utf-8':指定编码(推荐始终使用UTF-8)with语句:确保文件正确关闭,即使发生异常
1.2 写入多行内容
使用writelines()方法可以一次性写入多行:
lines = ["第一行\n", "第二行\n", "第三行\n"]
with open('multiline.txt', 'w', encoding='utf-8') as file:
file.writelines(lines)
1.3 追加内容到文件
使用'a'模式可以在文件末尾追加内容而不覆盖原有内容:
with open('example.txt', 'a', encoding='utf-8') as file:
file.write("这是追加的内容\n")
1.4 格式化写入
结合f-string或format()方法可以写入动态内容:
name = "张三"
age = 25
with open('formatted.txt', 'w', encoding='utf-8') as file:
file.write(f"姓名: {name}, 年龄: {age}\n")
# 或者使用format
file.write("职业: {}\n".format("工程师"))
2. 读取txt文件
2.1 读取整个文件
with open('example.txt', 'r', encoding='utf-8') as file:
content = file.read()
print(content)
2.2 逐行读取
with open('example.txt', 'r', encoding='utf-8') as file:
for line in file: # 迭代器方式逐行读取
print(line.strip()) # strip()去除行尾换行符
2.3 读取所有行到列表
with open('example.txt', 'r', encoding='utf-8') as file:
lines = file.readlines() # 返回包含所有行的列表
for i, line in enumerate(lines, 1):
print(f"第{i}行: {line.strip()}")
2.4 处理大文件
对于大文件,建议使用逐行读取或分块读取以避免内存问题:
# 方法1:逐行读取(内存友好)
with open('large_file.txt', 'r', encoding='utf-8') as file:
for line in file:
process_line(line) # 处理每一行的函数
# 方法2:分块读取
chunk_size = 1024 * 1024 # 1MB
with open('large_file.txt', 'r', encoding='utf-8') as file:
while True:
chunk = file.read(chunk_size)
if not chunk:
break
process_chunk(chunk) # 处理每个块的函数
3. 文件路径处理
3.1 相对路径与绝对路径
# 相对路径(相对于当前工作目录)
with open('./data/example.txt', 'r') as file:
...
# 绝对路径(推荐使用os.path或pathlib处理跨平台路径)
import os
file_path = os.path.join('C:', 'Users', 'username', 'Documents', 'example.txt')
with open(file_path, 'r') as file:
...
3.2 使用pathlib(Python 3.4+推荐)
from pathlib import Path
# 创建Path对象
file_path = Path('data/example.txt')
# 检查文件是否存在
if file_path.exists():
# 读取文件
content = file_path.read_text(encoding='utf-8')
print(content)
# 写入文件
file_path.write_text("新内容\n", encoding='utf-8')
4. 编码问题处理
4.1 常见编码问题
UnicodeDecodeError:通常是因为文件编码与指定编码不匹配UnicodeEncodeError:写入时使用了不支持的字符
4.2 解决方案
# 尝试常见编码
encodings = ['utf-8', 'gbk', 'gb2312', 'big5', 'latin1']
def read_with_fallback(filename):
for encoding in encodings:
try:
with open(filename, 'r', encoding=encoding) as file:
return file.read()
except UnicodeDecodeError:
continue
raise UnicodeDecodeError(f"无法解码文件 {filename},尝试了所有常见编码")
# 写入时忽略无法编码的字符(不推荐,除非必要)
with open('output.txt', 'w', encoding='utf-8', errors='ignore') as file:
file.write("包含特殊字符的文本")
5. 高级技巧
5.1 同时读写文件
使用'r+'模式可以同时读写文件:
with open('example.txt', 'r+', encoding='utf-8') as file:
content = file.read()
file.seek(0) # 移动指针到文件开头
file.write("新内容\n" + content) # 在开头插入内容
5.2 CSV格式文本处理
虽然CSV是专门格式,但常以.txt扩展名保存:
import csv
# 写入CSV格式文本
with open('data.txt', 'w', newline='', encoding='utf-8') as file:
writer = csv.writer(file)
writer.writerow(['姓名', '年龄', '城市'])
writer.writerow(['张三', 25, '北京'])
writer.writerow(['李四', 30, '上海'])
# 读取CSV格式文本
with open('data.txt', 'r', encoding='utf-8') as file:
reader = csv.reader(file)
for row in reader:
print(row)
5.3 JSON格式文本处理
对于结构化数据,JSON是更好的选择但仍可能保存为.txt:
import json
data = {
"name": "张三",
"age": 25,
"skills": ["Python", "数据分析"]
}
# 写入JSON
with open('data.txt', 'w', encoding='utf-8') as file:
json.dump(data, file, ensure_ascii=False, indent=4)
# 读取JSON
with open('data.txt', 'r', encoding='utf-8') as file:
loaded_data = json.load(file)
print(loaded_data)
6. 最佳实践
- 始终使用
with语句:确保文件正确关闭 - 明确指定编码:推荐始终使用UTF-8
- 处理异常:特别是文件不存在或权限问题时
- 避免硬编码路径:使用
os.path或pathlib - 大文件处理:使用逐行或分块读取
- 路径分隔符:跨平台时使用
os.path.join()或pathlib
完整示例
from pathlib import Path
def process_file_operations():
# 创建目录(如果不存在)
data_dir = Path('data')
data_dir.mkdir(exist_ok=True)
# 写入文件
file_path = data_dir / 'example.txt'
file_path.write_text(
"第一行文本\n"
"第二行文本\n"
"第三行文本\n",
encoding='utf-8'
)
# 读取并处理文件
if file_path.exists():
content = file_path.read_text(encoding='utf-8')
print("文件内容:")
print(content)
# 追加内容
file_path.write_text(
content + "\n这是追加的内容\n",
encoding='utf-8'
)
else:
print("文件不存在")
if __name__ == "__main__":
process_file_operations()
结论
Python提供了简单而强大的工具来处理txt文件的读写操作。从基本的文件操作到高级的路径处理和编码管理,掌握这些技术可以让你高效地处理各种文本数据场景。对于简单的任务,内置的open()函数通常就足够了;对于更复杂的路径操作或跨平台需求,pathlib模块提供了更现代的解决方案。记住始终考虑文件编码和异常处理,这将使你的代码更加健壮和可靠。
以上就是Python读写txt文件的多种方法的详细内容,更多关于Python读写txt文件的资料请关注脚本之家其它相关文章!
相关文章
python中三种高阶函数(map,reduce,filter)详解
在Python中,函数其实也是一种数据类型,今天重点给大家介绍python中三种高阶函数(map,reduce,filter)的相关知识,感兴趣的朋友一起看看吧2021-10-10
将PyInstaller打包的exe文件转换为pyc文件的方法
这篇文章主要介绍了如何将.exe文件转换为.py文件,然后使用PyLingual反编译器将.py文件反编译回源代码的过程,需要的朋友可以参考下2026-03-03
Python表格处理模块xlrd在Anaconda中的安装方法
本文介绍在Anaconda环境下,安装Python读取.xls格式表格文件的库xlrd的方法,xlrd是一个用于读取Excel文件的Python库,本文介绍了xlrd库的一些主要特点和功能,感兴趣的朋友一起看看吧2024-04-04


最新评论