简体   繁体   中英

How can I check if the first line of a CSV file has been written to?

So I'm running this Python script daily, but I want it to check if the header line is already written, write it if it isn't, and skip it if it is. I've tried doing things like reading the first line and setting a variable if there's input, but it hasn't worked. Here's my code:

def addDomainsToFile(domainList):
    date = time.strftime("%d:%m:%Y")
    fileName = 'MagDomains%s.csv' % date
    #Create file with the date as the name, this should be a week to week file, check if day is monday, if so,

    with open(fileName, 'ab+') as c:
        writer = csv.writer(c ,dialect= 'excel', delimiter= ',')
        for row in fileName:
            print row
        writer.writerow(['domain','ip','identifier','relationship', 'related To'])
        for item in domainList:
            writer.writerow([item, '', 'Related'])

How about checking if the file size of the csv is greater than zero? Should be enough for a rudimentary check:

import os
if os.path.getsize(fileName) == 0:
    write_header()

See if csv.Sniffer.has_header works for you.

https://docs.python.org/2/library/csv.html#csv.Sniffer

You can read the first row of your csv using csv.reader and the next function, and compare with your first row:

with open(fileName, 'ab+') as c:
    writer = csv.writer(c, dialect= 'excel', delimiter = ',')
    try :
         first_row = next(csv.reader(c, dialect = 'excel', delimiter = ','))
         for item in domainList:
                  writer.writerow([item, '', 'Related'])
    except StopIteration :
           writer.writerow(['domain', 'ip', 'identifier', 'relationship', 'related To'])
           for item in domainList:
               writer.writerow([item, '', 'Related'])

I needed to do this too and had to make some changes to Kasramvd's solution in order to make it work. When you use 'a+' mode, the file pointer is at the end. So you have to jump to the beginning of the file to read the first line. After reading the header (if there is one), you can jump back to the end to append to the file.

with open(filename, 'a+') as f:  # Just use 'w' mode in 3.x
    logger.info("Opened file")
    f.seek(0)  # jump to the beginning of the file
    try:
        header = csv.reader(f).next()
        dict_writer = csv.DictWriter(f, header)  # header found
    except StopIteration:  # no header found
        dict_writer = csv.DictWriter(f, my_dict.keys())
        dict_writer.writeheader()
    f.seek(0,2)  # jump back to the end of the file
    try:
        dict_writer.writerow(my_dict)
    except ValueError:
        # some keys from my_dict are not in header

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM