CSVWriter not saving data to file the moment I write it
The flush()
and close()
methods of the file object. Or use with
.
Use
with open('myfile.csv','wb') as myfile:
wrtr = csv.writer(myfile, delimiter=',', quotechar='"')
for row in rows:
wrtr.writerow([row.field1,row.field2,row.field3])
myfile.flush() # whenever you want
or
myfile = open('myfile.csv','wb')
wrtr = csv.writer(myfile, delimiter=',', quotechar='"')
for row in rows:
wrtr.writerow([row.field1,row.field2,row.field3])
myfile.flush() # whenever you want, and/or
myfile.close() # when you're done.
The nice thing about the first approach is that your file will also be automatically properly closed in case of an Exception.
If you want your file object to be anonymous, then it will only be closed when the program exits. When or whether it is flushed depends on the OS - so it might be never until exit.