1
我想在python中打開一個sql腳本,但這段代碼給內存錯誤,因爲sql腳本非常巨大(22GB!)。內存錯誤,同時在python中打開sql腳本
# Open and read the file as a single buffer
fd = open('prob.sql', 'r')
sqlFile = fd.read()
fd.close()
我想在python中打開一個sql腳本,但這段代碼給內存錯誤,因爲sql腳本非常巨大(22GB!)。內存錯誤,同時在python中打開sql腳本
# Open and read the file as a single buffer
fd = open('prob.sql', 'r')
sqlFile = fd.read()
fd.close()
在這種情況下避免read()
函數,因爲它試圖加載整個文件。
你可以通過行的文件行迭代:
with open('prob.sql', 'r') as fd:
for line in fd:
do_something(line)
隨着with
結構,你並不需要擔心關閉文件句柄。
查看其他選項here。
你的問題是什麼?如果文件的大小比可用內存大,則它不適合內存,句號。 –