2017-02-26 54 views
0

运行python代码时,我得到一个ValueError: I/O operation in closed file。我相信这是导致问题的部分:ValueError:关闭文件中的I/O操作

fn = './seenFrontPagePosts.txt' 

try: 
    f = open(fn, 'r+') 
except IOError: 
    f = open(fn, 'w+') 

try: 
    frontOld = json.loads(f.readline()) 
except: 
    frontOld = [] 

for post in redditFrontPage: 
    if str(post.subreddit) == subreddit: 
     print("We have a post on r/all! '{}'".format(post.title)) 
     if str(post.id) not in frontOld: 
      print("We haven't seen it before!") 
      message = post.reply(allMessage) 
      message.distinguish(sticky=True) 

      frontOld.append(str(post.id)) 
     else: 
      print("We have seen it before.") 
    f.seek(0) 
    f.truncate() 
    f.seek(0) 
    f.write(json.dumps(frontOld)) 
    f.close() 

如何修复错误?语法是关闭还是更复杂?

以下是完整的错误:

Traceback (most recent call last): 
    File "pythonCode.py", line 60, in <module> 
    f.seek(0) 
ValueError: I/O operation on closed file. 

回答

1

您是通过元素在列表redditFrontPage和循环内您要关闭文件f循环。那么在下一次迭代中,您正在尝试对文件执行一些操作,但它是关闭的。

您需要在循环中打开文件,或者不要关闭循环内的文件。

1

在最外层循环的一次迭代之后,f.close()关闭该文件。因此,下一次到达f.seek(0)时,它会遇到关闭的文件并引发错误。您需要在最外层循环的开始处做open

相关问题