简体   繁体   English

Python文件-每次打开都写入新行

[英]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. 我想做的是每次通过tkinter按钮调用AppViewer_SAVE函数时,它会打开文件并写入数据。 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: “ w +”模式:

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: 'a'模式:

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 . 以后,请查看Python文档中的open It states there explicitly "(note that'w+' truncates the file)". 它明确指出“(请注意,'w +'将截断文件)”。 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. 如果您使用的是Python 3,请确保明确引用所用Python版本的文档,因为open()接受的某些模式和参数是不同的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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