摘要:
同學們時常會遇到要處理大文件的情況,現在是大數據時代,有些文件動輒幾十個G,我們在處理這樣文件的時候一不小心就把內存撐爆了,或者程序被強制kill掉了。
原因是你一次性把文件的所有內容都讀取到內存裏面了。python裏面有方法可以一段一段的讀文件。
正文:
沒錯,就是用iterator,又叫迭代器,實例代碼如下。
cat test.py
f = open('data', 'r')
for line in f:
line = line.split(";;")
lines.append(line)
if len(lines) >= 10000:
# consume the lines which have been read
print lines
del lines[:]
if lines:
# consume the lines which have been read
print lines
cat data
73231701-201610;;shop_id::::73231701;;shop_name::::邂逅魅影;;platform_name::::xxxx;;shop_type::::個人賣家;;shop_loc::::xxx;;gold_seller::::否;;market_name::::taobao;;description::::NULL;;service::::NULL;;logistics::::NULL;;shop_owner::::洋洋103105;;create_time::::2012-08-15;;credit::::愛心4;;shop_age::::4;;co_name::::NULL;;shop_link::::https://shop73231701.example.com
73295319-201610;;shop_id::::73295319;;shop_name::::唯美爲你最美;;platform_name::::xxxx;;shop_type::::個人賣家;;shop_loc::::xxx;;gold_seller::::否;;market_name::::taobao;;description::::NULL;;service::::NULL;;logistics::::NULL;;shop_owner::::chenyan121166563;;create_time::::2012-08-20;;credit::::鑽石3;;shop_age::::4;;co_name::::NULL;;shop_link::::
https://shop73295319.example.com
上面的文件實際會很長,我這裏只是寫了兩行,僅供參考。
“for line in f”每次都只會讀取一行數據到內存,我們可以設置一個buffer,比如每10000行用list暫存下,處理完了之後再繼續讀取文件。
這樣就實現了一段一段的讀取文件內容到內存。是不是很酷!
趕緊試試吧!