user6039682
user6039682

Reputation:

Writing to file without losing data after crash

I have a file that I open before a loop starts, and I'm writing to that file almost at each iteration of the loop. Then I close the file once the loop has finished. So e.g. something like:

testfile = open('datagathered','w')
for i in range(n):
    ...
    testfile.write(line)

testfile.close()

Upvotes: 3

Views: 4720

Answers (2)

msencer
msencer

Reputation: 116

From the question I understood that you are talking about exceptions may occur at runtime and SIGINT.

You may use 'try-except-finally' block to achieve your goal. It enables you to catch both exceptions and SIGINT signal. Since the finally block will be executed either exception is caught or everything goes well, closing file there is the best choice. Following sample code would solve your problem I guess.

testfile = open('datagathered','w')
try:
     for i in range(n):
         ...
         testfile.write(line)
except KeyboardInterrupt:
    print "Interrupt from keyboard"
except:
    print "Other exception"
finally:
    testfile.close()

Upvotes: 6

marienbad
marienbad

Reputation: 1453

Use a context:

with open('datagathered','w') as f:
    f.write(data)

Upvotes: 2

Related Questions