【问题标题】:Can't Append to the File无法追加到文件
【发布时间】:2021-02-23 22:28:41
【问题描述】:

我正在尝试编写这个程序,如果用户打开现有文件,他们可以选择读取、重新开始或附加到它,但附加选项不起作用。这是为什么呢?

from sys import argv

file = input("Please open a file: ")
try:
    file = open(file, "r+")
    choice = input("""
    What would you like to do with this file?
    A) Read file
    B) Delete file and start over
    C) Append file
    """).lower().rstrip()
    if choice in "a":
        print(file.read())
    elif choice in "b":
        print("What would you like to write?")
        file.write(input())
    elif choice in "c":
        file = open(file, "a")
        print("What would you like to write?\n")
        file.write(input())
except:
    print("This is a new file.\n")
    file = open(file, "w")
    print("What would you like to save in this file?")
    file.write(input())```

【问题讨论】:

  • 请提供预期的minimal, reproducible example。这篇文章包含很多不相关的代码。
  • 我认为有必要显示所有这些,因为我试图让用户选择不附加。最后一个 elif 是 append 选项的位置
  • 您的通用异常处理将吞噬任何引发的异常,从而无法进行调试。

标签: python python-3.x file append


【解决方案1】:

您的代码的问题是您将变量file 分配给input("Please open a file: ") 中的用户输入,但在此之后您将其分配为file = open(file, "r+") 中的txt 文件。

因此,当您编写file = open(file, "a") 时,编译器读取的file 不是作为用户输入,而是作为打开的txt 文件。

你应该做的是给不同的变量起不同的名字

from sys import argv

filename = input("Please open a file: ")
try:
    file = open(filename, "r+")
    choice = input("""
    What would you like to do with this file?
    A) Read file
    B) Delete file and start over
    C) Append file
    """).lower().rstrip()
    if choice in "aA":
        print(file.read())
    elif choice in "bB":
        print("What would you like to write?")
        file.write(input())
    elif choice in "cC":
        file.close()
        file = open(filename, "a")
        print("What would you like to write?\n")
        file.write(input())
except:
    print("This is a new file.\n")
    file = open(file, "w")
    print("What would you like to save in this file?")
    file.write(input())

更新

正如 OneLiner 在 cmets 中所说,您应该始终在打开文件后关闭它们。正如他所说,这可以通过使用with open(filename, "a") as file: 轻松完成。除此之外,我还注意到了两件事。

首先,您不应该单独使用except,因为如果我尝试按ctrl+c,它将属于此异常。你应该写except FileNotFoundError,这样如果没有这样的文件,就会引发这个异常。

我注意到的第二件事是您使用名称file 作为变量的名称。问题是 file 已经在 python 中用于另一件事,所以最好使用另一个名称。在这种情况下,代码将是:

from sys import argv

filename = input("Please open a file: ")

try:
    with open(filename, "r+") as file_txt:
        pass

    choice = input("""
    What would you like to do with this file?
    A) Read file
    B) Delete file and start over
    C) Append file
    """).lower().rstrip()

    if choice == "a":
        with open(filename, "r") as file_txt: 
            print(file_txt.read())
    elif choice == "b":
        content = input("What would you like to write?\n")
        with open(filename, "w") as file_txt:
            file_txt.write(content)
    elif choice == "c":
        with open(filename, "a") as file_txt:
            content = input("What would you like to write?\n")
            file_txt.write(content)
            
except FileNotFoundError:
    print("This is a new file.\n")
    with open(filename, "w") as file_txt:
        content = input("What would you like to save in this file?\n")
        file_txt.write(content)

【讨论】:

  • 同时以正确的模式打开文件,完成后关闭。您可能需要考虑在每个 if 语句中使用“with open()”语句。
【解决方案2】:

使用"r+" 可以读写,但是指针在开头,这意味着“附加”实际上并不存在。如果我没记错的话,没有办法打开文件进行读取、写入和追加,因为没有办法沿着文件移动指针。

为了解决这个问题,我建议在每个 if 子句中单独打开文件。

如果此人想要阅读该文件,请使用"r" 打开它。 如果此人想要写入文件,则使用"w"打开它,如果此人想要追加到它,则使用"a"打开它。更多选项,例如两者的组合可以找到here

代码:

try:
    #removed:
    #file = open(file, "r+")
    choice = input("""
    What would you like to do with this file?
    A) Read file
    B) Delete file and start over
    C) Append file
    """).lower().rstrip()
    if choice in "a":
        file = open(file, "r")
        print(file.read())
    elif choice in "b":
        file = open(file, "w")
        print("What would you like to write?")
        file.write(input())
    elif choice in "c":
        file = open(file, "a")
        print("What would you like to write?\n")
        file.write(input())
except:
    print("This is a new file.\n")
    file = open(file, "w")
    print("What would you like to save in this file?")
    file.write(input())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-13
    • 2017-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-21
    相关资源
    最近更新 更多