Python读取TXT文件最常用的方法是使用内置的open()函数。通过指定文件路径和模式(如'r'表示读取),结合with语句可自动管理文件资源。with open('file.txt', 'r', encoding='utf-8') as f: 会安全打开文件,后续通过f.read()读取全部内容为字符串,或用f.readlines()获取行列表。此方式简洁高效,适合处理中小型文件。
Python怎么读取txt文件?
在Python中,读取TXT文件可以通过多种方式实现,以下是常见的几种方法及示例代码:
方法1:使用 open() 和 read() 一次性读取全部内容
python# 打开文件并读取全部内容with open('example.txt', 'r', encoding='utf-8') as file:content = file.read() # 返回字符串print(content)
说明:with 语句自动管理文件关闭,encoding 参数指定编码。
适用场景:文件较小,需要一次性处理全部内容。
方法2:逐行读取
方式1:readline() 逐行读取
pythonwith open('example.txt', 'r', encoding='utf-8') as file:line = file.readline() # 读取第一行while line:print(line.strip()) # 去除行尾换行符line = file.readline()
方式2:直接遍历文件对象
pythonwith open('example.txt', 'r', encoding='utf-8') as file:for line in file: # 自动逐行迭代print(line.strip())
说明:内存高效,适合大文件。
方法3:读取所有行到列表
pythonwith open('example.txt', 'r', encoding='utf-8') as file:lines = file.readlines() # 返回列表,每行为一个元素for line in lines:print(line.strip())
注意:大文件可能占用较多内存。
方法4:使用 pathlib
pythonfrom pathlib import Pathcontent = Path('example.txt').read_text(encoding='utf-8')print(content)
优势:面向对象的路径操作,代码更简洁。
常见问题处理
文件不存在:捕获 FileNotFoundError。
pythontry:with open('nonexistent.txt', 'r') as file:print(file.read())except FileNotFoundError:print("文件不存在!")
编码问题:明确指定 encoding(如 gbk、utf-8)。
二进制模式:用 'rb' 读取非文本文件。
总结
小文件:read() 或 readlines()。
大文件:逐行遍历(for line in file)。
简洁语法:pathlib.Path。
始终使用 with:确保文件正确关闭。
根据需求选择合适的方法即可!
以上就是关于Python怎么读取txt文件的详细解答,若需逐行处理大文件,推荐直接遍历文件对象,for line in open('file.txt'): print(line.strip())。此方法内存友好,避免一次性加载全部内容。pathlib模块提供面向对象的路径操作,使代码更简洁。注意处理异常并明确编码,确保兼容性。根据场景选择合适方法即可。