当前位置: 首页 > 图灵资讯 > 行业资讯> python如何读取大文件

python如何读取大文件

来源:图灵python
时间: 2025-11-10 16:42:44

banner89.png

Python可以通过两种方式读取大文件:第一种是使用yield生成器读取;二是:采用open()自带的方法生成迭代对象,这是一行一行的读取。

1、使用yield生成器读取

defreadPart(filePath,size=1024,encoding="utf-8"):
withopen(filePath,"r",encoding=encoding)asf:
whileTrue:
part=f.read(size)
ifpart:
yieldpart
else:
returnNone
filePath=r"filePath"
size=2048#每次读取指定大小的内容到内存
encoding='utf-8'
forpartinreadPart(filePath,size,encoding):
print(part)
#Processingdata

2、用open()自带的方法生成迭代对象,这是一行一行的读取

withopen(filePath)asf:
forlineinf:
print(line)
#Processingdata

欢迎查看python阅读文件相关操作文件:

python如何读取文件的数据?

Python知识更多,Python自学网

(推荐操作系统:windows7系统Python 3.9.1,DELL G3电脑。)