2017-05-27 86 views
0

現在學習python。 我有以下程序。Python - 它什麼時候寫入文件

  1. 爲什麼程序在最後一行之後不打印任何內容? 它看起來像「目標」沒有任何寫入的值。 (即使我打開實際的文件,有沒有值 這是爲什麼?

  2. 我嘗試添加上面的「target.close」的思想的文件不被寫入,直到該行線。這並不能工作。 那麼什麼是「target.close」的目的是什麼?

  3. 怎麼就是「target.truncate()」取得效果的時候了。該命令後,腳本暫停的輸入,如果我打開這個文件,我可以看到它所有的數據已經被刪除了。

from sys import argv 
script, filename = argv 

print (f"We are going to erase {filename}") 
print ("If you don't want that, press CTRL + C") 
print ("if you want that, press ENTER") 
input("? ") 

print("Opening the file.......") 
target = open(filename,"w+") 

print("Truncating the file....") 
target.truncate() 
print("Finished Truncating") 

print("Gimme 3 lines...") 

Line1 = input("Line 1: ") 
Line2 = input("Line 2: ") 
Line3 = input("Line 3: ") 

print("Writing these lines to the file") 

target.write(Line1 + "\n") 
target.write(Line2 + "\n") 
target.write(Line3 + "\n") 


print ("Finally, we close it") 
target.close 

input("Do you want to read the file now?") 
print(target.read()) 
+4

'target.close'不關閉文件; 'target.close()'確實。 –

回答

0

解決方案

target.close缺少一個括號,即它應該是target.close()

但看着你的意圖,看起來你想要做target.flush(),因爲你很快就會嘗試target.read() - 如果你關閉它,你將無法讀取文件。

它爲什麼會發生

默認情況下,一定量的寫入到文件數據的實際存儲到一個緩衝 - 內存 - 之前它實際上是寫入文件。如果要立即更新文件,則需要調用刷新方法,即target.flush()調用target.close()將自動刷新已緩衝的數據,因此target.close()也會更新文件,類似於target.flush()

2
target.close 

缺少()呼叫括號。這就是爲什麼沒有寫入。

然後,如果你想讀的文件,則需要重新打開它:

print(open(filename).read()) 
相關問題