1. 程式人生 > >python write函式,寫入檔案只能寫入一半

python write函式,寫入檔案只能寫入一半

示例:

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()



參考文件:

《python中 .write 無法向檔案寫入內容》