Python读写TXT文件需用open()函数配合with语句确保安全,读取可用read()、readline()或readlines(),写入用write()或writelines(),并指定编码防乱码。

Python读取TXT文件,核心在于使用内置的
open()
read()
readline()
readlines()
open()
write()
writelines()
with
处理TXT文件,无论是读还是写,其基本骨架都围绕着Python的
open()
读取TXT文件:
最常见的场景就是把文件内容读出来。这里有几种方式,取决于你希望如何处理文件内容。
立即学习“Python免费学习笔记(深入)”;
一次性读取整个文件: 如果你确定文件不大,或者需要一次性处理所有内容,
read()
try:
with open('my_document.txt', 'r', encoding='utf-8') as file:
content = file.read()
print("文件全部内容:")
print(content)
except FileNotFoundError:
print("错误:文件 'my_document.txt' 未找到。")
except UnicodeDecodeError:
print("错误:文件编码不匹配,尝试其他编码。")这里
'r'
encoding='utf-8'
逐行读取文件: 对于大多数文本文件处理,逐行读取更为常见,也更节省内存,尤其是在处理大文件时。
try:
with open('my_document.txt', 'r', encoding='utf-8') as file:
print("\n逐行读取内容:")
for line_num, line in enumerate(file, 1):
print(f"第 {line_num} 行: {line.strip()}") # .strip() 去除行尾的换行符
except FileNotFoundError:
print("错误:文件 'my_document.txt' 未找到。")
except UnicodeDecodeError:
print("错误:文件编码不匹配,尝试其他编码。")直接迭代文件对象是最优雅且高效的逐行读取方式。
读取所有行到一个列表中: 如果你需要将文件的所有行作为一个列表来处理,
readlines()
try:
with open('my_document.txt', 'r', encoding='utf-8') as file:
lines = file.readlines()
print("\n所有行以列表形式:")
for line_num, line in enumerate(lines, 1):
print(f"列表第 {line_num} 项: {line.strip()}")
except FileNotFoundError:
print("错误:文件 'my_document.txt' 未找到。")
except UnicodeDecodeError:
print("错误:文件编码不匹配,尝试其他编码。")注意,
readlines()
写入TXT文件:
写入文件同样需要选择合适的模式。
写入新内容(覆盖模式): 使用
'w'
new_content = "这是我写入的第一行内容。\n这是第二行,带换行符。\n"
with open('output.txt', 'w', encoding='utf-8') as file:
file.write(new_content)
file.write("再加一行,不带换行符可能和上一行连起来。\n")
print("\n'output.txt' 已在'w'模式下写入。")追加内容(追加模式): 使用
'a'
append_content = "这是追加的新内容。\n"
with open('output.txt', 'a', encoding='utf-8') as file:
file.write(append_content)
print("\n'output.txt' 已在'a'模式下追加内容。")写入多行内容:
writelines()
list_of_lines = ["列表中的第一行。\n", "列表中的第二行。\n", "列表中的第三行。\n"]
with open('output_list.txt', 'w', encoding='utf-8') as file:
file.writelines(list_of_lines)
print("\n'output_list.txt' 已使用writelines写入。")需要注意的是,
writelines()
\n
这几乎是Python文件操作中最常见、也最让人头疼的问题之一。当你的TXT文件读出来一堆“锟斤拷”或者莫名其妙的符号时,八成是编码惹的祸。简单来说,文件编码就像是一种语言,你的Python程序需要用正确的“语言”去解读文件。如果文件是UTF-8编码,你却用GBK去读,那肯定就“鸡同鸭讲”了。
Python的
open()
# 假设文件是GBK编码
try:
with open('example_gbk.txt', 'r', encoding='gbk') as file:
content = file.read()
print("成功读取GBK文件:", content)
except UnicodeDecodeError:
print("错误:尝试GBK编码失败。")
except FileNotFoundError:
print("文件未找到。")
# 假设文件是UTF-8编码
try:
with open('example_utf8.txt', 'r', encoding='utf-8') as file:
content = file.read()
print("成功读取UTF-8文件:", content)
except UnicodeDecodeError:
print("错误:尝试UTF-8编码失败。")
except FileNotFoundError:
print("文件未找到。")如何确定文件的编码?
这其实是个经验活,但也有工具可以帮忙:
文本编辑器查看: 很多高级文本编辑器(如VS Code, Sublime Text, Notepad++)在右下角或状态栏会显示当前文件的编码。
尝试常见的编码: UTF-8是目前最通用的编码,其次是GBK(中文Windows系统常见)、Latin-1(或ISO-8859-1,处理西欧语言)。你可以依次尝试这些编码,直到成功。
使用第三方库: 像
chardet
# 需要先安装:pip install chardet
import chardet
def detect_encoding(file_path):
with open(file_path, 'rb') as f: # 以二进制模式读取,因为chardet需要字节流
raw_data = f.read(10000) # 读取文件开头一部分数据进行猜测
result = chardet.detect(raw_data)
return result['encoding']
file_path = 'my_document.txt'
detected_encoding = detect_encoding(file_path)
print(f"猜测文件 '{file_path}' 的编码是: {detected_encoding}")
if detected_encoding:
try:
with open(file_path, 'r', encoding=detected_encoding) as file:
content = file.read()
print("使用猜测编码读取成功:", content)
except UnicodeDecodeError:
print("错误:猜测编码未能成功解码。")即便
chardet
当你的TXT文件达到GB级别时,直接使用
file.read()
file.readlines()
Python的文件对象本身就是一个迭代器。这意味着你可以像遍历列表一样遍历它,每次只加载一行到内存中,这正是处理大文件的关键。
def process_large_file_line_by_line(file_path):
line_count = 0
total_chars = 0
print(f"开始处理大型文件: {file_path}")
try:
with open(file_path, 'r', encoding='utf-8') as file:
for line in file: # 核心:直接迭代文件对象
line_count += 1
total_chars += len(line)
# 在这里对每一行进行你的具体处理
# 例如:解析数据、筛选特定内容、写入另一个文件等
if line_count % 100000 == 0: # 每处理10万行打印一次进度
print(f"已处理 {line_count} 行...")
print(f"文件处理完成。总行数: {line_count}, 总字符数: {total_chars}")
except FileNotFoundError:
print(f"错误:文件 '{file_path}' 未找到。")
except UnicodeDecodeError:
print(f"错误:文件 '{file_path}' 编码不匹配,请检查。")
# 假设有一个非常大的文件 'big_data.txt'
# process_large_file_line_by_line('big_data.txt')这种逐行迭代的方式,无论文件有多大,内存占用都保持在一个较低且稳定的水平,因为它每次只在内存中保留当前处理的这一行数据。
更高级一点的思考:生成器(Generators)
如果你需要对每一行进行一些预处理,并且这些预处理结果需要被后续的多个步骤使用,可以考虑使用生成器函数。生成器提供了一种惰性计算的方式,它不会一次性生成所有结果,而是在每次需要时才计算并返回下一个结果。
def read_lines_as_processed_data(file_path):
"""一个生成器函数,用于从文件中逐行读取并进行简单处理"""
try:
with open(file_path, 'r', encoding='utf-8') as file:
for line_num, line in enumerate(file, 1):
# 假设我们只是想把每行数据转为大写,并返回行号和处理后的内容
processed_line = line.strip().upper()
yield line_num, processed_line # 使用yield关键字
except FileNotFoundError:
print(f"错误:文件 '{file_path}' 未找到。")
except UnicodeDecodeError:
print(f"错误:文件 '{file_path}' 编码不匹配。")
# 使用生成器
# for num, data in read_lines_as_processed_data('big_data.txt'):
# # 对data进行进一步操作
# # print(f"处理后的第 {num} 行: {data}")
# pass生成器在处理大型数据集时非常有用,它将数据的生成和消费解耦,使得代码更清晰、内存效率更高。
写入文件时最怕的就是不小心把原有数据冲掉,或者在多进程/多线程环境下写入冲突。Python的
open()
'w'
# 第一次运行:创建文件并写入
with open('safe_write.txt', 'w', encoding='utf-8') as f:
f.write("这是第一次写入的内容。\n")
print("safe_write.txt (w模式) 第一次写入完成。")
# 第二次运行:会覆盖第一次写入的内容
with open('safe_write.txt', 'w', encoding='utf-8') as f:
f.write("这是第二次写入的内容,覆盖了第一次。\n")
print("safe_write.txt (w模式) 第二次写入完成,内容已被覆盖。")'a'
# 第一次运行:创建文件并写入
with open('safe_append.txt', 'a', encoding='utf-8') as f:
f.write("这是第一次追加的内容。\n")
print("safe_append.txt (a模式) 第一次追加完成。")
# 第二次运行:会在文件末尾添加新内容
with open('safe_append.txt', 'a', encoding='utf-8') as f:
f.write("这是第二次追加的内容。\n")
print("safe_append.txt (a模式) 第二次追加完成,内容已在末尾添加。")'x'
open()
FileExistsError
try:
with open('safe_exclusive.txt', 'x', encoding='utf-8') as f:
f.write("这是通过'x'模式创建并写入的内容。\n")
print("safe_exclusive.txt (x模式) 创建并写入成功。")
except FileExistsError:
print("错误:文件 'safe_exclusive.txt' 已存在,'x'模式拒绝覆盖。")
# 再次尝试运行,会触发FileExistsError
try:
with open('safe_exclusive.txt', 'x', encoding='utf-8') as f:
f.write("这行内容永远不会被写入,因为文件已存在。\n")
except FileExistsError:
print("第二次尝试创建'safe_exclusive.txt'失败,因为文件已存在。")确保数据写入磁盘:flush()
close()
即便你使用了正确的模式,数据也可能不会立即写入物理磁盘。Python的文件操作通常会有内部缓冲区,数据会先写入缓冲区,达到一定量或文件关闭时才真正写入磁盘。
with
close()
file.flush()
with open('flush_example.txt', 'w', encoding='utf-8') as f:
f.write("这行内容可能还在缓冲区。\n")
f.flush() # 强制将缓冲区内容写入磁盘
print("数据已强制刷新到磁盘。")
# 即使程序此时崩溃,这行内容也应该已经写入了。
f.write("这行内容在flush之后写入。\n")
# 文件退出with块时会自动关闭和刷新。理解这些模式和机制,能让你在Python中进行文件操作时更加从容和安全。
以上就是python如何读取一个txt文件_python读写TXT文件的基本操作的详细内容,更多请关注php中文网其它相关文章!
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号