
可以通过两种方法利用python读取大文件:第一种是利用yield生成器读取;第二种是:利用open()自带方法生成迭代对象,这个是一行一行的读取。
1、利用yield生成器读取
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | def readPart(filePath, size=1024, encoding= "utf-8" ):
with open(filePath, "r" ,encoding=encoding) as f:
while True:
part = f.read(size)
if part:
yield part
else :
return None
filePath = r "filePath"
size = 2048 # 每次读取指定大小的内容到内存
encoding = 'utf-8'
for part in readPart(filePath,size,encoding):
print (part)
# Processing data
|
2、利用open()自带方法生成迭代对象,这个是一行一行的读取
1 2 3 4 | with open(filePath) as f:
for line in f:
print (line)
# Processing data
|
python读取文件相关操作文档欢迎查看:
python如何读取文件的数据
更多Python知识可以关注Python自学网
(推荐操作系统:windows7系统、Python 3.9.1,DELL G3电脑。)