在Python中,读取文件数据主要通过内置的open()函数实现,Python中读取文件常用open()函数,搭配with语句可自动管理资源。'r'表示只读模式,encoding指定编码,此方法简洁且避免忘记关闭文件。在Python中,有多种方法可以读取文件中的数据,跟着小编一起详细了解下吧。
一、python怎么读取文件中的数据?
打开文件
使用open()函数,指定文件路径和模式:
pythonfile = open('example.txt', 'r', encoding='utf-8') # 推荐显式指定编码
读取内容
读取全部内容:read()
pythondata = file.read() # 返回字符串
逐行读取:readline() 或 readlines()
pythonline = file.readline() # 读取单行lines = file.readlines() # 返回列表,每行为一个元素
迭代读取(推荐大文件):
pythonfor line in file:print(line.strip()) # 逐行处理
关闭文件
pythonfile.close() # 释放资源
二、推荐用法:with语句
pythonwith open('example.txt', 'r', encoding='utf-8') as file:content = file.read() # 或逐行处理# 无需手动close(),代码块结束后自动关闭
三、常见模式与参数
模式描述
'r'只读(默认)
'w'写入(覆盖原有内容)
'a'追加(在文件末尾添加)
'b'二进制模式(如'rb'读取图片)
'+'读写模式(如'r+')
四、完整示例
示例1:读取文本文件
pythonwith open('data.txt', 'r', encoding='utf-8') as f:for line in f:print(f"Line: {line.strip()}") # 去除行尾换行符
示例2:写入文件
pythonwith open('output.txt', 'w', encoding='utf-8') as f:f.write("Hello, Python!\nSecond line.")
示例3:读取CSV文件
pythonimport csvwith open('data.csv', 'r', encoding='utf-8') as f:reader = csv.reader(f)for row in reader:print(row) # 每行是一个列表
五、注意事项
文件路径:建议使用绝对路径或确保相对路径正确。
异常处理:用try-except捕获文件不存在等错误:
pythontry:with open('missing.txt', 'r') as f:print(f.read())except FileNotFoundError:print("文件不存在!")
大文件处理:避免直接read(),用逐行迭代或chunk分块读取。
在Python中读取文件数据是一个常见的操作,通常包括打开文件、读取文件内容、处理数据和关闭文件几个步骤。通过以上方法,可以灵活处理文本、二进制文件等不同需求。