可以通過兩種方法利用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培訓機構:千鋒教育。