[英]Python: Readline returns error after 10 lines
I'm trying to use readline on file in a for loop. 我正在尝试在for循环中对文件使用readline。 The problem is that I start getting I/O errors.
问题是我开始遇到I / O错误。 It seems that I get I/O error after 10 readlines.
似乎经过10条阅读线后出现I / O错误。
Here is my function: 这是我的功能:
def getAll():
with open("nodes2.txt", "r+") as f:
for i in range(0, 200):
print "**%s**"%(i)
try:
file = f.readline()
file = file[:-1]
# print "*%s*" % (file)
entities = getAllPagesEntities(file)
# print entities
for en in entities:
try:
dict = getFirmAttributes(en)
printToFile(dict)
except Exception,e:
with open("log_getFirmAttributes.txt","a") as f:
f.write(str(e))
f.write("\n")
except Exception,e:
with open("log_readFile.txt","a") as f:
f.write(str(e))
f.write("\n")
Here is a printed catched exception: 这是捕获的打印异常:
I/O operation on closed file
I think that this problem can't be caused by another used functions so I don't attach them here. 我认为这个问题不能由其他使用过的函数引起,所以我不在这里附加它们。 I thought that it is caused by the file used but when I try to readline 200 and print them, everything works perfect.
我以为这是由使用的文件引起的,但是当我尝试读取200行并打印它们时,一切正常。
with open("nodes2.txt", "r+") as f:
for i in range(0, 200):
print f.readline()
Have you any idea what could be the problem? 你知道可能是什么问题吗? Thanks
谢谢
Following lines in the except
block overwrites f
causing open file to be closed. except
块中的以下行覆盖f
导致打开的文件被关闭。
with open("log_readFile.txt","a") as f:
f.write(str(e))
f.write("\n")
Change the name f
for the file for appending to another name will solve the problem: 更改文件的名称
f
以附加到另一个名称将解决此问题:
with open("log_readFile.txt", "a") as logf:
logf.write(str(e))
logf.write("\n")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.