之前接觸的數據,無論是csv還是txt格式,都比較小,最大也就幾百兆。在讀取過程中不會遇到內存崩潰的現象。
最近,項目中接收到的數據竟然比電腦內存還要大 ,讀取過程中經常遇到memoryError錯誤,於是開始研究了關於大文件讀取;於此參考了以下博客:
https://blog.csdn.net/u011847043/article/details/81069105
談到“文本處理”時,我們通常是指處理的內容。
Python 將文本文件的內容讀入可以操作的字符串變量非常容易。文件對象提供了三個“讀”方法: .read()、.readline() 和 .readlines()。。
read() 一次性讀取讀取整個文件,將文件存儲在一個字符串變量中。當文件接近或者大於內存時會產生memoryError的錯誤。
readline() 和 readlines() 之間的差異是后者一次讀取整個文件,同 read()。
readlines() 自動將文件內容分析成一個行的列表,該列表可以由 Python 的 for ... in ... 結構進行處理。
另一方面,.readline() 每次只讀取一行,通常比 readlines() 慢得多。僅當沒有足夠內存可以一次讀取整個文件時,應該使用 .readline()。
with open('filepath', 'r', encoding = 'utf-8') as f:
while True:
line = f.readline() # 逐行讀取
if not line: # 到 EOF,返回空字符串,則終止循環
break
Operate(line) #對每行數據進行處理
分塊讀取(實用靠譜)
將文檔按塊進行讀取
def read_in_chunks(filePath, chunk_size=1024*1024):
file_object = open(filePath,'r',encoding='utf-8')
while True:
chunk_data = file_object.read(chunk_size)
if not chunk_data:
break
yield chunk_data
if __name__ == "__main__":
filePath = "C:/Users/Public/Documents/data/user_data.csv"
for chunk in read_in_chunks(filePath):
print(chunk)