Skip to content Skip to sidebar Skip to footer

Checking If The First Cell Of A Csv Is Blank In Python

I'm trying to write a dictionary to a CSV. It's in a loop so each iteration through the loop should append the latest dictionary to the end of my CSV. I wanted to add a feature wh

Solution 1:

The simplest approach is probably to try to read the first row:

has_headers = True# Assumes the file existswithopen('DataOutput.csv') as f:
    reader = csv.reader(f)
    try:
        headers = next(reader)
    except StopIteration:
        has_headers = False# Open in append mode and add headers if necessary

Alternatively, if you delete the file rather than just clearing it out, you could could try to create it and write the headers each time.

try: 
    # Open in exclusive creation modewithopen('DataOutput.csv', 'x') as f:
        writer = csv.writer(f)
        writer.writerow(headers)
except FileExistsError:
    passwithopen('DataOutput.csv', 'a') as f:
    ... 

Solution 2:

I was able to get this to work:

withopen('some_file.csv', 'a', newline='') as csv_a, open('some_file.csv','r') as csv_r:
    reader = csv.reader(csv_r)
    writer = csv.DictWriter(csv_a, sorted_closes.keys())
    data = [row for row in reader] #turns all the cells into a listif data[0][0]=='':
        writer.writeheader()
        writer.writerow(sorted_closes)
        # or whatever you want to do if the first cell is emptyelse:
        writer.writerow(sorted_closes)
        # or whatever you want to do if the first cell is NOT empty

Solution 3:

You can try this way. It worked for me

withopen('dataFile.csv', 'r') as csvfile:
        csvReader = csv.reader(csvfile)
        forrowin csvReader:
            if row[0] in (None, ""):
                -- TODO for empty

Post a Comment for "Checking If The First Cell Of A Csv Is Blank In Python"