关闭后无法重新打开文件

时间:2019-02-09 17:56:07

标签: python file valueerror

我一直在使用一些用于印刷诗歌的代码。该代码的目的是使边框适合诗歌的大小。但这与我的问题无关。我一直在尝试获取重新打印文件的代码,一行一行,但是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 个答案:

答案 0 :(得分:0)

您的步骤是:

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

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

简短示例:

def a():
    var = 2

var = 1
a()

print(var) #prints 1

您可以在mgilson's answer on a question that covers similar problemthe 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()