关闭后无法重新打开文件

Failure to Re-open File after Closing

我一直在使用一些旨在打印一首诗的代码。代码的目标是制作适合诗歌大小的边框。但这与我的问题无关。我一直在尝试获取代码以逐行重新打印文件,但返回的是 ValueError: I/O operation on closed file.

我试图通过在文件关闭后重新打开文件并在 def poemprint(poem): 函数完成后重新打开它来解决这个问题。但是这两种方法都失败了。我不知道从这里去哪里。

import os
os.system("clear")

quitw=["no","n","ney","ne","nope","nuh-uh","nuh","noh","neigh","nye","negative","please no","no               please","quit","stop","q","s"]
harlem=open("harlem.txt","r")
hhop=open("hhop.txt","r")
poems={"1":harlem,"2":hhop}
poemname={"1":"harlem.txt","2":"hhop.txt"}

#10 lines of def quit() code

def poemprint(poem):
    print("╭"+"-"*60+"╮")
    print("|  Poem Printer [v0.5]"+" "*39+"|")
    print("⊢"+"-"*60+"⊣")
    print("|"+" "*60+"|")
    for a in poem: #line where error occurs
        b=57-len(a)
        print("|    "+a[0:len(a)-1]+(" "*b)+"|")
    print("|"+" "*60+"|")
    print("╰"+"-"*60+"╯")
    poem.close()
    if f=="harlem.txt": #doesn't work
        harlem=open("harlem.txt","r")
    elif f=="hhop.txt":
        hhop=open("hhop.txt","r")

c=(input("Enter a Poem: "))
if c not in quitw:
    while c not in quitw:
        while c.lower() in poems:
            os.system("clear")
            f=poemname[c]
            poemprint(poems[c])
            c=(input("Enter a Poem: "))
            if c in quitw:
                quit()
            else:
                continue
        os.system("clear")
        print("Invalid input.")
        c=(input("Enter a Poem: "))
else:
    quit()

注意:quit() 是一个已定义的函数,用于完全停止代码。

这是我第二次要哈莱姆诗后应该看到的:

    ╭------------------------------------------------------------╮
    |  Poem Printer [v0.5]                                       |
    ⊢------------------------------------------------------------⊣
    |                                                            |
    |    Harlem by Langston Hughes                               |
    |                                                            |
    |      What happens to a dream deferred?                     |
    |                                                            |
    |        Does it dry up                                      |
    |        like a raisin in the sun?                           |
    |        Or fester like a sore—                              |
    |        And then run?                                       |
    |        Does it stink like rotten meat?                     |
    |        Or crust and sugar over—                            |
    |        like a syrupy sweet?                                |
    |                                                            |
    |        Maybe it just sags                                  |
    |        like a heavy load.                                  |
    |                                                            |
    |        Or does it explode?                                 |
    |                                                            |
    ╰------------------------------------------------------------╯

相反,我得到:

    ╭------------------------------------------------------------╮
    |  Poem Printer [v0.5]                                       |
    ⊢------------------------------------------------------------⊣
    |                                                            |
    Traceback (most recent call last):
      File "main.py",line 44, in <module>
        poemsprint(poems[c])
      File "main.py",line 27, in poemprint
        for a in poem:
    ValueError: I/O operation of closed file.

您的步骤是:

  1. 您在 harlem 变量中打开一个文件
  2. 您使用 harlem 参数调用 poemprint 函数。此 harlem 在函数内部 引用 作为 poem
  3. 您关闭了 poem 引用的文件(它在 harlem 函数之外)
  4. 创建一个仅存在于函数内部的新变量harlem
  5. 功能完成后,你有harlem作为一个关闭的文件

发生这种情况是因为 poemprint 中的 harlem 和外面的那个是不同的对象。

简短示例:

def a():
    var = 2

var = 1
a()

print(var) #prints 1

您可以在 mgilson's answer on a question that covers similar problem and in the Python documentation 中阅读更多相关信息。

如何修复:

不要打开文件,而是保留它们的名称。

poems={"1":"harlem.txt","2":"hhop.txt"}

然后修改函数以获取文件名作为参数并在函数内部打开文件

def poemprint(poem):
    print("╭"+"-"*60+"╮")
    print("|  Poem Printer [v0.5]"+" "*39+"|")
    print("⊢"+"-"*60+"⊣")
    print("|"+" "*60+"|")

    poem = open(poem, "r") #This
    for a in poem:
        b=57-len(a)
        print("|    "+a[0:len(a)-1]+(" "*b)+"|")
    print("|"+" "*60+"|")
    print("╰"+"-"*60+"╯")
    poem.close()
    #End of the function

现在应该可以了。

Enter a Poem: 1
╭------------------------------------------------------------╮
|  Poem Printer [v0.5]                                       |
⊢------------------------------------------------------------⊣
|                                                            |
|    Roses are red                                           |
|    Violets are blue                                        |
|                                                            |
╰------------------------------------------------------------╯
Enter a Poem: 1
╭------------------------------------------------------------╮
|  Poem Printer [v0.5]                                       |
⊢------------------------------------------------------------⊣
|                                                            |
|    Roses are red                                           |
|    Violets are blue                                        |
|                                                            |
╰------------------------------------------------------------╯
Enter a Poem: 

完整代码如下:

import os
os.system("clear")

quitw=["no","n","ney","ne","nope","nuh-uh","nuh","noh","neigh","nye","negative","please no","no               please","quit","stop","q","s"]
poems={"1":"harlem.txt","2":"hhop.txt"}

#10 lines of def quit() code

def poemprint(poem):
    print("╭"+"-"*60+"╮")
    print("|  Poem Printer [v0.5]"+" "*39+"|")
    print("⊢"+"-"*60+"⊣")
    print("|"+" "*60+"|")

    poem = open(poem, "r") #This
    for a in poem:
        b=57-len(a)
        print("|    "+a[0:len(a)-1]+(" "*b)+"|")
    print("|"+" "*60+"|")
    print("╰"+"-"*60+"╯")
    poem.close()

c=(input("Enter a Poem: "))
if c not in quitw:
    while c not in quitw:
        while c.lower() in poems:
            os.system("clear")
            f=poems[c]
            poemprint(poems[c])
            c=(input("Enter a Poem: "))
            if c in quitw:
                quit()
            else:
                continue
        os.system("clear")
        print("Invalid input.")
        c=(input("Enter a Poem: "))
else:
    quit()