如何修复Python中附加模式下的文件覆盖?

2024-04-19 03:32:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用python用tkinter编写一个register(例如,一个school one)程序,并且我试图在每个人单击submit时向register添加一个新的人,但是所发生的一切是它正在覆盖以前的名称,这意味着它被保存的文件只有一个名称。你知道吗

有人对如何解决这个问题有什么建议吗?你知道吗

更清楚的是:register\u info和listedes\u info是注册者的名字和最新保存到文件中的人的名字。你知道吗

这是我代码的一部分:

def create_register():
    register_info = registername.get()
    listees_info = listees.get()
    list_of_registers=os.listdir()
    if register_info in list_of_registers:
        file=open(register_info,"w")
        file.close()
        Label(create, text = "Register Created", fg = "green" ,font = ("calibri", 8)).pack()
    with open(register_info,"a") as file_info:
        file_info.write(register_info+"\n")
        file_info.write(listees_info+"\n")
        file_info.close()

Tags: 文件ofinfo名称registerclosegetcreate
2条回答

传递给wopen模式(在您的file=open(register_info,"w")行中)告诉python您要打开文件进行写入。根据设计,这将除去文件中的任何其他内容,并将光标放在开头。听起来像是要打开文件并在末尾附加信息,而不覆盖任何内容。你知道吗

为此,您应该使用appenda模式。这将打开文件进行写入,并将光标放在文件末尾。你知道吗

所以,你需要说open(register_info, "a")。你知道吗

我还建议切换到上下文管理器,以确保在发生任何意外行为时关闭文件。您可以这样做:

with open(register_info, "a") as file:
    # Any code that needs to use "file" here

有关文件打开模式的更多信息(摘自我的另一个答案):

r: Opens the file in read-only mode. Starts reading from the beginning of the file and is the default mode for the open() function.

rb: Opens the file as read-only in binary format. Places the cursor at the start of the file.

r+: Opens a file for reading and writing. Places the cursor at the beginning of the file.

w: Opens in write-only mode. Places the cursor at the beginning of the file. This will overwrite any existing file with the same name. It will create a new file if one with the same name doesn't exist.

wb: Same behavior as w, except the file is opened in binary mode.

w+: Opens a file for writing and reading. Replaces all content and creates the file if it doesn't exist. This mode is used when you need to write to an empty-file and potentially read from it later in your code (before closing).

wb+: Same behavior as w+ except the file is in binary mode.

a: Opens a file for appending new information to it. The cursor is placed at the end of the file. A new file is created if one with the same name doesn't exist.

ab: Same behavior as a except the file is in binary mode.

a+: Opens a file for both appending and reading. The cursor is placed at the beginning of the file.

ab+: Same as a+ except the file is in binary mode.

您应该修复此部分:

    if register_info in list_of_registers:
        file=open(register_info,"w")
        file.close()

w模式下打开此文件时,实际上是在重置它。你知道吗

相关问题 更多 >