運行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.