1. 程式人生 > >python中 .write 無法向檔案寫入內容

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

問題程式碼如下

links = open("new")
out = open("out.txt","w+")
for link in links:
    out.write(link+"\n")

問題原因:

當沒有使用flush()或close()時,要寫入的內容依然在緩衝區中,沒有寫入檔案,如果中途終止,檔案裡就會沒有內容。

解決方法:

links = open("new")
out = open("out.txt","w+")
for link in links:
    out.write(link+"\n")
    out.flush()