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.sstatic.net/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 })

3
  • You can maybe compare the first row and see if headers are added and not add it the second time Commented May 10, 2019 at 10:56
  • See this : stackoverflow.com/questions/32312309/… Commented May 10, 2019 at 11:01
  • thanks, this seems abit hard. Commented May 10, 2019 at 11:12

1 Answer 1

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 })

Sign up to request clarification or add additional context in comments.

11 Comments

sorry for late reply, but your code doesn't work, it somehow isn't write anything, just an empty csv file.
the code runs without any error, but somehow the csv file was empty as this link. imgur.com/r8bnUWO
StopIteration exception was thrown which I was not handling previously.
I have updated your code but when I run it it's not even write the file which is data.csv
but I have tried to create a "data.csv" by hand before I execute the code , and the data is written lol , as this imgur.com/KLerJUP
|

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.