【问题标题】:ValueError: I/O operation on closed file error "txt database"ValueError: I/O 操作关闭文件错误“txt 数据库”
【发布时间】:2013-11-08 21:09:06
【问题描述】:

大家好,还在这里:)

我得到 ValueError: I/O operation on closed file 错误。

db = open(r"C:\Users\PC\Desktop\db.txt", "a+")
print("""-Type 1 for add film
-Type 2 for see your films
""")
while True:
    enter = input("Please Enter: ")

    if enter == "1":
        film=input("Enter film: ")
        db.write(film + "\n")
        db.close()

    elif enter == "2":
        print("Your's films: ")
        db.seek(0)
        print(db.read())

        db.close()



    elif giris == "":
        print("Please type something!")


    else:
        print("Error!")

当我输入 1 时,我添加了电影,然后我再次输入 2 以查看我的电影。我得到 ValueError: I/O operation on closed file error :(

【问题讨论】:

    标签: python database python-3.x io


    【解决方案1】:

    错误正是它所说的。关闭文件后,您正在尝试写入文件。有两种解决方案:

    1. close() 调用移出循环。

      while True:
          # do stuff
      
      db.close()
      
    2. 在循环中打开文件。

      while True:
          db = open(r"C:\Users\PC\Desktop\db.txt", "a+")
          ...
      

    【讨论】:

      【解决方案2】:

      您在while 循环中执行db.close(),这会在迭代之间关闭文件。这是你错误的根源。我会将db.close() 移到脚本的末尾。这比每次迭代都重新打开文件更有效。

      如果您需要在遍历循环时刷新输出,请使用flush(),即db.flush()

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-09-27
        • 2016-03-06
        • 1970-01-01
        • 2016-07-21
        • 2015-07-20
        • 1970-01-01
        相关资源
        最近更新 更多