Reputation: 3568
I have a simple program that writes to a file in a for loop (30k+ iterations). I noticed that the program is taking abnormally long to finish, after which I decided to kill it. The file it is writing to has 29900 lines created withing 30s and the remaining 100 are not written - the program doesn't exit and it takes hours to do so.
Once I killed it, it finished writing the remaining 100 or so lines.
f1 = open('parts.txt', "w")
for line in lines:
category = line[2]
f1.write(category + '\n')
print('------- done -------')
f1.close()
Is there anything obvious that I am missing?
Upvotes: 0
Views: 1863
Reputation: 49
I spent a while trying to figure out why this was happening to me - it turns out it wasn't my Python code's fault at all for me: my IDE (PyCharm) doesn't seem to refresh (or at least often) the file tree whilst the program is running. However, the files were still generated, and looking at the file explorer/finder (or unfocusing/refocusing PyCharm), the files were generated.
I know this wasn't the answer for OP, but for anyone else who's having issues down the line (and searching around and comes across this) and nothing done in Python seems to work - check if the file has been generated with your system's file browser!
Upvotes: 1
Reputation: 1366
Use a with statement, this way the file is always closed independent of the exit status.
with open('parts.txt', 'w') as fw:
for line in lines:
category = line[2]
fw.write(category + '\n')
print('----- done ------')
Upvotes: 1