現在學習python。 我有以下程序。Python - 它什麼時候寫入文件
爲什麼程序在最後一行之後不打印任何內容? 它看起來像「目標」沒有任何寫入的值。 (即使我打開實際的文件,有沒有值 這是爲什麼?
我嘗試添加上面的「target.close」的思想的文件不被寫入,直到該行線。這並不能工作。 那麼什麼是「target.close」的目的是什麼?
怎麼就是「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())
'target.close'不關閉文件; 'target.close()'確實。 –