簡體   English   中英

Python文件-每次打開都寫入新行

[英]Python files - Write to new line each time opened

我想做的是每次通過tkinter按鈕調用AppViewer_SAVE函數時,它會打開文件並寫入數據。 我的問題是,每次調用和寫入函數時,它不會寫入新行,它只會覆蓋第一行中的數據,以下是代碼:

def Appviewer_SAVE(self):
    target = open("saved", "w+")
    target.write("%s\t" % App_InfoTrans0())
    target.write("%s\t" % App_InfoTrans1())
    target.write("%s\n" % App_InfoTransfer_Gender) #\n doesn't make a difference here
    target.close()

將您的代碼更改為:

def Appviewer_SAVE(self):
    target = open("saved", "a")
    target.write("%s\t" % App_InfoTrans0())
    target.write("%s\t" % App_InfoTrans1())
    target.write("%s\n" % App_InfoTransfer_Gender) #\n doesn't make a difference here
    target.close()

“ w +”模式:

打開一個文件進行讀寫。 如果文件存在,則覆蓋現有文件。 如果該文件不存在,請創建一個新文件以進行讀寫。

'a'模式:

打開一個文件進行追加。 如果文件存在,則文件指針位於文件的末尾。 也就是說,文件處於附加模式。 如果該文件不存在,它將創建一個新文件進行寫入。

您可以在此鏈接上查看所有文件模式

您想要以以下方式在附加模式下打開文件

open(filename, 'a') 

盡管附加模式有時在行為上有特定於平台的差異,所以另一個選擇是在寫入模式下打開並手動搜索到結尾

f = open(filename, 'w') 
f.seek(0, os.SEEK_END) 

以后,請查看Python文檔中的open 它明確指出“(請注意,'w +'將截斷文件)”。 如果您使用的是Python 3,請確保明確引用所用Python版本的文檔,因為open()接受的某些模式和參數是不同的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM