0

I'm using python 2.7 and I have a program that when I take picture from the camera ,the data(phase,date,time,name of image) will be stored in CSV file each time when the image being capture. This is the csv file looks like when the short code below executed. https://i.stack.imgur.com/hzMTe.png

As you can see the "headers" which are 'Phase', 'Date', 'Time','Name' will be printed out again in the next line when the image being capture.

I want the headers just print one time on the top of csv file. As I strolling around some websites there is [newline=''] keyword that should work but as I'm using python 2.7 it's not possible.

Any help would be greatly appreciated.

import csv

with open('data.csv', 'a') as f:

                fieldnames = ['Phase', 'Date', 'Time','Name']
                thewriter = csv.DictWriter(f, fieldnames = fieldnames)
                thewriter.writeheader()

                thewriter.writerow({'Phase': _phase, 'Date' : 
                 _currentDT.date(), 'Time' : _currentDT.time(),
                                    'Name' : _nameImage })

frankenstein
  • 125
  • 2
  • 11

1 Answers1

0

If you want a simple solution you can do something like this (not the most efficient solution)

import csv

with open('data.csv', 'r+') as f:
    reader = csv.reader(f)
    row1 = []

    try:
        row1 = next(reader)
    except StopIteration:
        print("No data is written to file yet")

    fieldnames = ['Phase', 'Date', 'Time', 'Name']
    thewriter = csv.DictWriter(f, fieldnames=fieldnames)

    if row1 != fieldnames:
        thewriter.writeheader()

    thewriter.writerow({'Phase': _phase, 'Date' : 
     _currentDT.date(), 'Time' : _currentDT.time(),'Name' : _nameImage })

Z.Amir
  • 195
  • 1
  • 12