4

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.

1
  • i got the solution Added code csvFile.close() Commented Feb 26, 2014 at 14:18

3 Answers 3

9

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)
Sign up to request clarification or add additional context in comments.

Comments

3

You should use strftime() to create the date and time in the format that you need such as

mydate = datetime.datetime.now()
csvstr = datetime.datetime.strftime(mydate, '%Y, %m, %d, %H, %M, %S')

This is besides closing or flushing the file to force the buffer output. The way that you asked the question implied that you were not seeing output data after the python program had exited, which would have closed the file as part of the exit processing.

I would also remember to make the header row, the first row in the output file.

Comments

0

i got the solution Added following code

csvFile.close()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.