可以通过两种方法利用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相关知识,请关注IT培训机构:瀚银百科。