Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write current datetime to a csv file in python?

Tags:

python

I used following code for writing the datetime to a csv file.

csvdata=[datetime.datetime.now()]
csvFile=open("Datetime.csv","w")
Fileout=csv.writer(csvFile, delimiter=',',quoting=csv.QUOTE_ALL)
Fileout.writerow(csvdata)

Eventhough the file is creating it have no data in it.What should i do in extra for getting the data in csv.

like image 740
mystack Avatar asked Oct 30 '25 19:10

mystack


1 Answers

The problem is that the writing of the file is buffered, and does not happen immediately. You should close your file descriptor to flushes any unwritten data:

csvFile.close()

Or just use with statement (recommended):

csvdata = [datetime.datetime.now()]
with open("Datetime.csv","w") as csvFile:
    Fileout = csv.writer(csvFile, delimiter=',', quoting=csv.QUOTE_ALL)
    Fileout.writerow(csvdata)
like image 176
defuz Avatar answered Nov 01 '25 08:11

defuz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!