Python读取txt文件需用open()函数配合with语句确保资源释放,推荐逐行迭代或分块读取大文件,并明确指定encoding解决编码问题。

Python读取txt文件主要依赖内置的
open()
read()
readline()
readlines()
write()
with
在Python中进行文件读写,核心在于
open()
1. 打开文件: 使用
open()
encoding='utf-8'
# 读取模式 # 'r' - 只读(默认模式),文件不存在会报错 # 'w' - 只写,如果文件存在会清空内容,不存在则创建新文件 # 'a' - 追加模式,如果文件存在,新内容会添加到文件末尾,不存在则创建新文件 # 'r+' - 读写模式,文件指针在开头 # 'w+' - 读写模式,清空文件内容或创建新文件 # 'a+' - 读写模式,文件指针在末尾(写入时),读取时在开头
2. 读取文件内容: 一旦文件被打开,你就可以使用文件对象提供的方法来读取数据。
read()
with open('example.txt', 'r', encoding='utf-8') as f:
content = f.read()
print(content)readline()
with open('example.txt', 'r', encoding='utf-8') as f:
first_line = f.readline()
second_line = f.readline()
print(f"第一行: {first_line.strip()}") # .strip()去除换行符
print(f"第二行: {second_line.strip()}")readlines()
with open('example.txt', 'r', encoding='utf-8') as f:
lines = f.readlines()
for line in lines:
print(line.strip())with open('example.txt', 'r', encoding='utf-8') as f:
for line in f:
print(line.strip())3. 写入文件内容: 使用
write()
write(string)
write()
\n
# 写入新内容(会覆盖旧内容)
with open('output.txt', 'w', encoding='utf-8') as f:
f.write("这是第一行内容。\n")
f.write("这是第二行内容。\n")
# 追加内容
with open('output.txt', 'a', encoding='utf-8') as f:
f.write("这是追加的第三行。\n")4. 错误处理: 文件操作时可能会遇到
FileNotFoundError
PermissionError
try...except
try:
with open('non_existent_file.txt', 'r', encoding='utf-8') as f:
content = f.read()
print(content)
except FileNotFoundError:
print("错误:文件不存在,请检查路径。")
except Exception as e:
print(f"发生了一个未知错误: {e}")编码问题,说实话,是我在Python文件操作中遇到最多的“拦路虎”之一。你兴冲冲地写好代码,运行,结果屏幕上跳出一堆乱码,或者更糟,直接一个
UnicodeDecodeError
立即学习“Python免费学习笔记(深入)”;
解决这个问题,核心思想就是明确地告诉Python你正在处理的文件是什么编码格式。默认情况下,Python 3在打开文件时会尝试使用系统的默认编码(比如在Windows上可能是GBK,在Linux上通常是UTF-8),但如果文件实际编码与系统默认不符,问题就来了。
最直接、最推荐的做法是:在open()
encoding
# 假设你的文件是UTF-8编码
with open('my_document.txt', 'r', encoding='utf-8') as f:
content = f.read()
print(content)
# 如果你知道文件是GBK编码(中文Windows系统常见)
with open('legacy_file.txt', 'r', encoding='gbk') as f:
content = f.read()
print(content)
# 甚至是一些比较少见的,比如Latin-1
with open('iso_file.txt', 'r', encoding='latin-1') as f:
content = f.read()
print(content)当你遇到
UnicodeDecodeError
utf-8
gbk
latin-1
errors
open()
encoding
errors
errors='ignore'
errors='replace'
?
�
# 慎用!这会丢失信息
with open('problem_file.txt', 'r', encoding='utf-8', errors='ignore') as f:
content = f.read()
print(content)这种方法虽然能让程序跑起来,但你得到的数据可能是不完整的或有偏差的,所以只应作为最后的手段,并且要清楚其副作用。我的建议是,从源头解决编码问题,确保文件以正确的编码保存,或者在读取时使用正确的编码参数。
with
with
with
想象一下,你打开了一扇门(文件),进去拿东西。拿完东西后,你是不是应该把门关上?如果忘了关,这扇门就一直开着,别人可能进不来,或者风雨会进来。文件也是一样,当你用
open()
f.close()
这就可能导致一系列问题:
而
with
with
__enter__
with
__exit__
__exit__
这意味着,无论你的代码在
with
try...finally
f.close()
# 没有使用with语句的写法(不推荐)
f = open('data.txt', 'r', encoding='utf-8')
try:
content = f.read()
print(content)
except Exception as e:
print(f"处理文件时出错: {e}")
finally:
f.close() # 必须手动关闭
# 使用with语句的写法(推荐)
with open('data.txt', 'r', encoding='utf-8') as f:
content = f.read()
print(content)
# 文件在with块结束时自动关闭,即使有异常很明显,
with
处理大文件,比如几个GB甚至几十GB的日志文件或数据集,如果直接用
f.read()
f.readlines()
MemoryError
1. 逐行迭代(Line-by-Line Iteration)
这是处理文本大文件最常用、最有效的方式之一。Python的文件对象本身就是可迭代的。当你直接在
for
def process_large_text_file_line_by_line(filepath):
line_count = 0
with open(filepath, 'r', encoding='utf-8') as f:
for line in f:
# 在这里处理每一行数据
# 比如:解析JSON、过滤特定内容、统计词频等
# print(line.strip()) # 打印时去除换行符
line_count += 1
if line_count % 100000 == 0:
print(f"已处理 {line_count} 行...")
print(f"文件处理完毕,总行数: {line_count}")
# 示例调用
# process_large_text_file_line_by_line('large_log.txt')这种方法内存占用极低,因为它一次只处理一行,非常适合日志文件分析、数据清洗等场景。
2. 分块读取(Reading in Chunks)
对于二进制文件或者那些不以行划分的文本文件(比如巨大的XML、CSV文件,你可能想一次读取固定大小的数据块),
f.read(size)
size
def process_large_binary_file_in_chunks(filepath, chunk_size=4096): # 默认4KB
total_bytes_read = 0
with open(filepath, 'rb') as f: # 注意这里是'rb',读取二进制
while True:
chunk = f.read(chunk_size)
if not chunk: # 读取到空块,表示文件已读完
break
# 在这里处理数据块
# 比如:计算哈希值、查找特定字节序列、传输数据块等
# print(f"读取了 {len(chunk)} 字节的块")
total_bytes_read += len(chunk)
if total_bytes_read % (1024 * 1024 * 100) == 0: # 每100MB打印一次
print(f"已处理 {total_bytes_read / (1024 * 1024):.2f} MB...")
print(f"文件处理完毕,总字节数: {total_bytes_read}")
# 示例调用
# process_large_binary_file_in_chunks('large_data.bin')这种方式对于处理图像、视频、归档文件等二进制数据非常有效。
chunk_size
3. 使用mmap
对于非常非常大的文件,如果你的操作系统支持内存映射文件(大多数现代操作系统都支持),Python的
mmap
import mmap
import os
def search_in_large_file_with_mmap(filepath, search_term):
if not os.path.exists(filepath):
print(f"文件 {filepath} 不存在。")
return False
with open(filepath, 'r+b') as f: # 'r+b' 读写二进制模式
# 使用mmap.mmap创建内存映射
# length=0表示映射整个文件
mm = mmap.mmap(f.fileno(), 0)
try:
# 在映射的内存中查找字节序列
# 注意:search_term也需要是字节串
if mm.find(search_term.encode('utf-8')) != -1:
print(f"找到了 '{search_term}'。")
return True
else:
print(f"未找到 '{search_term}'。")
return False
finally:
mm.close() # 务必关闭mmap对象
# 示例调用
# with open('large_text_for_mmap.txt', 'w', encoding='utf-8') as f:
# f.write("This is a very long file with some important text inside it." * 100000)
# search_in_large_file_with_mmap('large_text_for_mmap.txt', 'important text')mmap
选择哪种策略,取决于你的文件类型、文件大小以及你想要对数据进行的操作。对于大多数文本大文件,逐行迭代通常是最佳选择,兼顾了简单性和效率。
以上就是python怎么读取txt文件_python文件读写步骤的详细内容,更多请关注php中文网其它相关文章!
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号