[英]Python: Readline returns error after 10 lines
我正在嘗試在for循環中對文件使用readline。 問題是我開始遇到I / O錯誤。 似乎經過10條閱讀線后出現I / O錯誤。
這是我的功能:
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")
這是捕獲的打印異常:
I/O operation on closed file
我認為這個問題不能由其他使用過的函數引起,所以我不在這里附加它們。 我以為這是由使用的文件引起的,但是當我嘗試讀取200行並打印它們時,一切正常。
with open("nodes2.txt", "r+") as f:
for i in range(0, 200):
print f.readline()
你知道可能是什么問題嗎? 謝謝
except
塊中的以下行覆蓋f
導致打開的文件被關閉。
with open("log_readFile.txt","a") as f:
f.write(str(e))
f.write("\n")
更改文件的名稱f
以附加到另一個名稱將解決此問題:
with open("log_readFile.txt", "a") as logf:
logf.write(str(e))
logf.write("\n")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.