Solar
Solar

Reputation: 43

File is not closing properly

I'm not sure why, but the file 'refined.txt' is not closing properly (see code below). I get a Windows error ("The process cannot access the file because it is being used by another process") when I try to rename the file in the last line of code.

It is important that this file is renamed because this piece of code is part of a for loop, so if I don't rename the file to something unique it will get written over.

I am hoping that someone will be able to tell me why the file isn't closing properly.

Code:

    of = open('refined.txt')
    d=of.readlines()

    for line in d[:20]:
        #some code

    of.close()    
    os.rename('refined.txt', new)

Upvotes: 0

Views: 66

Answers (1)

Vasili Syrakis
Vasili Syrakis

Reputation: 9591

Try using the with statement to open the file instead, and see if that makes any difference.

with open('refined.txt') as of:
    d = of.readlines()

for line in d[:20]:
    #some code

os.rename('refined.txt', new)

Upvotes: 1

Related Questions