Kreatronik
Kreatronik

Reputation: 199

Python: Writing to file-->file empty

In a script data is written like so:

result = open("c:/filename.csv", "w")
result.write("\nTC-"+str(TC_index))

The .csv-file is filled with data in a while(1) loop. I run the script in Eclipse and exit by hitting the stop button. Unfortunately most of the time when I open the file it is completely empty.

Is there a way to fix that?

Upvotes: 1

Views: 1398

Answers (1)

jez
jez

Reputation: 15349

To ensure a content is flushed and written to file without having to close the file handle:

import os
# ...

result.write("\nTC-"+str(TC_index))
result.flush()
os.fsync(result)

But of course, if you break the loop manually there's no guarantee you won't break it between the write and the flush, thereby failing to get the last line. I'm unfamiliar with the Eclipse stop button but perhaps it stops execution by causing a KeyboardInterrupt exception to be raised. If so you could always catch that and explicitly close the file. Better still, use a with statement which will cause that to happen automatically:

with open("c:/filename.csv", "w") as result:
    for TC_index in range(100):  # or whatever loop
        result.write("\nTC-"+str(TC_index))
        # flush & fsync here if still necessary (but might not be)

Upvotes: 3

Related Questions