简体   繁体   中英

Python files - Write to new line each time opened

What i'm trying to do is each time the function AppViewer_SAVE is called via a tkinter button, for it to open the file and write the data. My problem is each time the function is called and writes, it doesn't write to a new line, it just overwrites the data that is on the first line, heres the code:

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()

Change your code to:

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+' Mode:

Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.

'a' Mode:

Opens a file for appending. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.

You can over view all the mode of files at this link

You want to either open the file in append mode with

open(filename, 'a') 

Though append mode sometimes has some platform-specific differences in behavior, so another option is to open in write mode and manually seek to the end

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

In the future, check the Python docs for open . It states there explicitly "(note that'w+' truncates the file)". If you're working with Python 3 make sure to refer explicitly to the docs for the Python version you are using, as some of the modes and arguments accepted by open() are different.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM