简体   繁体   中英

Python: Readline returns error after 10 lines

I'm trying to use readline on file in a for loop. The problem is that I start getting I/O errors. It seems that I get I/O error after 10 readlines.

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.

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.

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:

with open("log_readFile.txt", "a") as logf:
    logf.write(str(e))
    logf.write("\n")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM