ValueError:关闭文件中的I / O操作

时间:2017-02-26 23:36:47

标签: python reddit praw

我在运行python代码时得到ValueError: I/O operation in closed file。我相信这是引起问题的部分:

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.

2 个答案:

答案 0 :(得分:1)

您正在循环遍历列表redditFrontPage中的元素,并在该循环中关闭文件f。那么在下一次迭代中,您尝试对文件执行某些操作但它已关闭。

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

答案 1 :(得分:1)

在最外层循环的一次迭代之后,f.close()关闭文件。因此,下次到达f.seek(0)时,它会遇到关闭的文件并抛出错误。您需要在最外层循环的开头执行open