因此,我一直在嘗試撰寫一個代碼,專門更改某個檔案夾中 .txt 檔案中的文本 - 到目前為止它可以作業。但是有一個問題:它不會實時更新(在代碼內部),直到我重復代碼(如,我選擇'Y'),但是當我使用腳本時,它會在檔案外部實時更改本身。
#Fun??o
def coca():
print("Write your anotation:")
escolha = input()
arquivo1 = open('doc.txt', 'a')
arquivo1.write(escolha)
arquivo1.write(" ")
print("Your anotation:")
f = open("DOC.txt", "r")
print(f.read())
arquivo1.write("\n")
# Main
x = 0
# Loop
while x < 1:
coca()
repetir = input("Do you wish to add anything else to your annotation? Y or N ").lower()
if repetir.upper() == 'N':
print('Goodbye.')
x = x 1
基本上,假設我在輸入中輸入了一個名為“這條象牙腿是推動我的動力,魚叉刺入天空”的注釋,當它隨后列印文本時,它顯示一個空白的石板(如果檔案上沒有任何內容)或者在我添加新注釋之前的檔案內容 - 所以如果我在 .txt 上寫了“兄弟們,如果你想贏得勝利,請折斷你的背脊和槳葉”,“象牙腿”部分就不會顯示起來,直到我再次啟動代碼。
我相信這是因為文本只會在主代碼完成后更新,這意味著 print 函式只顯示doc.txt上當前的內容,因為腳本尚未完成。
順便說一句,對不起我的英語。這不是我的母語!
uj5u.com熱心網友回復:
寫入后關閉 arquivo1 檔案。
def coca():
print("Write your anotation:")
escolha = input()
arquivo1 = open('doc.txt', 'a')
arquivo1.write(escolha)
arquivo1.write(" \n")
arquivo1.close()
print("Your anotation:")
f = open("DOC.txt", "r")
print(f.read())
f.close()
現在這可以正常作業。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/519563.html
下一篇:Python中的多付計算錯誤
