【问题标题】:How do i write again to a file after reading it (or make a loop for the read and write process )?读取文件后如何再次写入文件(或为读写过程创建循环)?
【发布时间】:2017-06-29 03:51:11
【问题描述】:

我正在编写一个程序,允许您写入文件然后查看它。我的程序只有在我先添加文本然后查看时才有效。另一方面,当我读取文件然后尝试再次写入时

我会在这一行出现这个错误file.write(addtext + "\n")

io.UnsupportedOperation: not writable

这是我的代码:

file = open("notebook.txt","r")
file = open("notebook.txt","w")
while True:
    print("(1) Read the notebook \n(2) Add note \n(3) Empty the notebook \n(4) Quit")
    selection = int(input("Please select one:"))
    if selection == 1:
        file = open("notebook.txt","r")
        content = file.read()
        print(content)
    elif selection == 2:
        addtext = input("Write a new note:")
        file.write(addtext + "\n") 

我曾尝试在读取过程后添加 file.close 或替换这行代码file = open("notebook.txt","r"),但它们都不起作用。

【问题讨论】:

  • 编辑您的问题并格式化您的代码,使其看起来更清晰

标签: python python-3.x


【解决方案1】:

我认为 notebook.txt 存在。否则在使用此代码之前创建它(或修改此代码以管理此文件不存在的情况)。

您不能先同时写入和读取文件。先读后写,使用with范式在使用后自动关闭文件,避免打开文件过多操作系统错误(例如,如果您忘记在IOError之后关闭文件)

做:

_file = "notebook.txt"
while True:
    print("(1) Read the notebook) \n"
          "(2) Add note \n"
          "(3) Empty the notebook \n"
          "(4) Quit")
    selection = int(input("Please select one:"))
    if selection == 1:
        with open(_file, "r") as filename:
            content = filename.read()
            print(content)
    elif selection == 2:
        with open(_file, "a") as filename:
            note = input("Your note:")
            filename.write(note)
    elif selection == 3:
        with open(_file, "w") as filename:
            filename.write('')
    elif selection == 4:
        break

不要使用 file 作为变量名,因为它是一个内置函数,在 Python 2 中参见 here(关键字 here 也是如此)

【讨论】:

  • 谢谢。您的解决方案对我有用。但我仍然可以在没有代码 with 的情况下使其工作
【解决方案2】:

我不确定您的要求是什么,但我看了一下您的代码,并尽我所能看看我能做什么。

所以我首先导入了 os 模块,以检查启动时是否存在 txt 文件。如果是这样,那么我打开它阅读。如果没有,那就打开写吧。

对于 while 循环,第一个 if 语句打开 txt 文件进行读取,然后文件中的行存储在 content 通过 readlines() 函数。然后我使用 for 循环来打印 content 中的每一行。

第二个 if 语句打开文件进行追加,我使用 writelines() 函数写入用户的输入。

这是我添加到您的代码中的代码:

import os

if os.path.isfile("notebook.txt"):
    f = open("notebook.txt", "r+")
    f.close()
else:
    f = open("notebook.txt", "w")
    f.close()

while True:
    print("(1) Read the notebook \n(2) Add note \n(3) Empty the notebook \n(4) Quit")
    selection = int(input("Please select one:"))
    if selection == 1:
        f = open("notebook.txt", "r+")
        content = f.readlines()
        for line in content:
            print(line)
        f.close()
    elif selection == 2:
        addtext = input("Write a new note:")
        f = open("notebook.txt", "a")
        f.writelines(addtext + "\n")
        f.close()
    elif selection == 3:
        f = open("notebook.txt", "w")
        with f as filename:
            filename.write("")
        print("Notebook emptied.")
    elif selection == 4:
        break

如果这对你有用,如果你有任何问题,请告诉我。

【讨论】:

  • 谢谢你。添加 f = open("notebook.txt", "a") 使我的程序正常工作。也感谢你教我如何删除文本。
【解决方案3】:

尝试替换

file = open("notebook.txt", "r")

 file = open("notebook.txt", "rw")

您可能需要先关闭文件才能重新打开它。

【讨论】:

  • 我已经重写了你的代码。这很好用 #/bin/python3 file = open("notebook.txt", "w") while True: print("(1) Read the notebook \n(2) Add note \n(3) Empty the notebook \ n(4) Quit") selection = int(input("请选择")) if selection == 1: file = open("notebook.txt", "r") content = file.read() print(content) elif selection == 2: addtext = input("写一个新笔记:") file.write(addtext) file.close()
  • Exception ValueError: must have just one of create/read/write/append mode
猜你喜欢
  • 2013-07-17
  • 1970-01-01
  • 2021-03-22
  • 2012-09-15
  • 2018-06-20
  • 1970-01-01
  • 1970-01-01
  • 2013-03-31
  • 1970-01-01
相关资源
最近更新 更多