0

I have a program which will run on a cron job and write the output to a CSV file.

I get it to write correctly but I would like to make the program write headers on the first row when the file is created. Is there a way of the program checking if there are any rows in the CSV file and, if not, writing the headers.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Sam Collins
  • 443
  • 5
  • 13
  • Yes, of course, but this isn't a code-writing service; what have you tried, and what exactly is the problem with it? – jonrsharpe Nov 01 '14 at 16:02
  • possible duplicate of [python how to check file empty or not](http://stackoverflow.com/questions/2507808/python-how-to-check-file-empty-or-not) – anon582847382 Nov 01 '14 at 16:03
  • I will try seeing if a file is empty I hadn't though of that and I have looked about and tried to write the code if there where no lines present but that didn't seem to work – Sam Collins Nov 01 '14 at 16:07

1 Answers1

0

Just use a flag:

headers_written = False

then when writing rows:

if not headers_written:
    writer.writerow(headers)
    headers_written = True

writer.writerow(somerow)

You'd actually postpone creating the writer until you are sure you have stuff to write:

writer = None

# ...

if not writer:
    writer = csv.writer(open(filename, 'wb'))
    writer.writerow(headers)

writer.writerow(somerow)
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343