python write函式,寫入檔案只能寫入一半
阿新 • • 發佈:2018-11-29
示例:
writeFile = open('write.txt', 'w')
for i in range(1, 1000):
data = str(i) + 'aaaaaaaaaaaaaaaaaaaaaaaaaa\n'
writeFile.write(data)
結果生成的檔案只有798行:
問題原因:
要寫入的內容依然在緩衝區中,沒有寫入檔案
兩種解決方法:
1.使用flush()函式;
writeFile = open('write.txt', 'w') for i in range(1, 1000): data = str(i) + 'aaaaaaaaaaaaaaaaaaaaaaaaaa\n' writeFile.write(data) writeFile.flush()
2.正確的呼叫close()函式;
writeFile = open('write.txt', 'w')
for i in range(1, 1000):
data = str(i) + 'aaaaaaaaaaaaaaaaaaaaaaaaaa\n'
writeFile.write(data)
writeFile.close()
參考文件: