0

I have this code:

def write_csv(path, inputdata):
    with open(path, 'w', errors='ignore', newline='') as newfile:
        writer = csv.writer(newfile, dialect='excel')
        writer.writerows(inputdata)

I would like to write the date at the top of the CSV file. I tried to include

writer.writerow(datetime.date.today())

This as expected really returned _csv.Error: iterable expected, not datetime.date How else could I do it? Include it as the fieldnames and write as a DictWriter? I'm not confident that would work though.

PythonIsBae
  • 368
  • 3
  • 10
  • Try to convert the date object to string first using strftime(): https://thispointer.com/python-how-to-convert-datetime-object-to-string-using-datetime-strftime/ – NewPythonUser May 27 '20 at 20:57
  • This writes it to the CSV in this form: `2,7,-,M,a,y,-,2,0,2,0`. This is clearly not very useful as I need it as `27 May 2020` – PythonIsBae May 27 '20 at 22:03
  • It looks like you've already got some answers. Question, though: Is the CSV file blank to begin? Or does it contain data already? To add the date in after data is present, there is a clever answer by Hai Vu at https://stackoverflow.com/questions/28162358/append-a-header-for-csv-file – patmcb May 27 '20 at 22:52
  • @patmcb file gets truncated at the start. This would work however I’m using this for lots of CSVs so easier to just writerow it does matter where it happens really – PythonIsBae May 27 '20 at 23:04

1 Answers1

1

writerow takes an iterable. If you have only one string, you have to wrap it in [] or writerow will iterate over single characters in the iterable string instead of iterating over objects in an iterable list.

import csv
import datetime

with open('test.csv', 'w', newline='') as newfile:
        writer = csv.writer(newfile)
        writer.writerow([f'{datetime.date.today():%d-%B-%Y}'])

Output:

27-May-2020
Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251
  • Returns: `AttributeError: 'list' object has no attribute 'keys'`, using your exact line of code copied into my function. I also defined `datetime.date.today` as `todays_date` and `writer.writerow([todays_date])`, this returned the same error. – PythonIsBae May 27 '20 at 23:21
  • 1
    @PythonIsBae Code above works in Python 3.6. Did you try the *exact* code above? I can't fix your code if I can't see it, but my crystal ball says you switched to a `csv.DictWriter`, because `.writerow()` would expect a dictionary which has a `.keys()` method. – Mark Tolonen May 28 '20 at 00:04