【问题标题】:open() in append mode is not behaving as expected附加模式下的 open() 未按预期运行
【发布时间】:2020-07-24 03:34:20
【问题描述】:

我正在尝试创建一个程序,询问用户他们想对文件执行什么操作,读取/附加/删除文件。

FileName = open(input("Enter file name: "))
ReadFile = FileName.read()
Decision = input("Do you want to read/delete/append to the file?: ")
if Decision == "read":
    print(ReadFile)
    FileName.close()
elif Decision == "append":
    Append = input("Type what you want to add: ")
    with open("FileName","a") as file:
        file.write(Append)

但是当我检查文件时它没有附加它

【问题讨论】:

标签: python-3.x file append


【解决方案1】:

发生这种情况是因为您实际上并没有打开同一个文件。您要求用户输入以指定文件的位置以读取该文件,但是如果他们选择“附加”该文件,则您让他们附加到与他们指定的文件无关的文件中。您让用户附加一个名为"FileName" 的文件。当用户选择“追加”时,您已将该字符串硬编码为文件的位置。

这里,FileName 不是代表文件位置的字符串。这是一个代表文件的对象。

FileName = open(input("Enter file name: "))

您让用户在文件路径中输入了一个字符串,但您没有存储该字符串值。您将该值用于open() 一个文件以供阅读。

在这里,您正在打开一个名为 "FileName" 的文件,该文件可能是 python 启动的目录,因为此处没有可见的路径。

    with open("FileName","a") as file:
        file.write(Append)

查看你的起始目录,看看你是否创建了一个名为"FileName"的新文件。

请记住,如果您使用mode="a" 打开一个文件,但该文件不存在,则会创建一个新文件。 https://docs.python.org/3/library/functions.html#open

我也想借此机会通知您PEP8, Python's styling guide. 这不是法律,但遵循它会帮助其他 Python 程序员更快地帮助您。

话虽如此,请考虑让您的代码 sn-p 看起来更像以下代码:

filename = input("Enter file name: ")
decision = input("Do you want to read/delete/append to the file?: ")
if decision == "read":
    with open(filename) as file:
        print(file.read())

elif decision == "append":
    append = input("Type what you want to add: ")
    with open(filename, "a") as file:
        file.write(append)

【讨论】:

  • 谢谢你解释得很好
猜你喜欢
  • 2020-11-23
  • 2022-01-02
  • 2015-10-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-22
  • 1970-01-01
相关资源
最近更新 更多