Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How to check if cell in CSV file is empty?

Tags:

python

csv

I have a CSV file that I'm reading in Python and I want the program to skip over the row if the first column is empty. How do I do this?

Right now I have:

with open('testdata1.csv', 'rU') as csvfile:
        csvreader = csv.reader(csvfile)
        for row in csvreader:
            if row[0] = null:
                #?????

How do I: 1) Check for empty cells in the CSV; and 2) tell the reader to skip the row?

Thanks guys.

like image 774
korakorakora Avatar asked Dec 10 '15 02:12

korakorakora


3 Answers

with open('testdata1.csv', 'r') as csvfile:
    csvreader = csv.reader(csvfile)
    for row in csvreader:
        print(row)
        if not row[0]:
             print("12")

Reference: How do I detect missing fields in a CSV file in a Pythonic way?

like image 175
Kit Fung Avatar answered Oct 14 '22 06:10

Kit Fung


You could use try and except.

for row in csvreader:
        try:
               #your code for cells which aren't empty
        except:
               #your code for empty cells
like image 26
Palak Bansal Avatar answered Oct 14 '22 06:10

Palak Bansal


I tried out what happens if you print and empty row and it returns [] (empty brackets)... so just check for that.

with open('testdata1.csv', 'rU') as csvfile:
    csvreader = csv.reader(csvfile)
    for row in csvreader:
        if row == []:
            continue
        #do stuff normally
   
like image 41
Maxim Gärtner Avatar answered Oct 14 '22 06:10

Maxim Gärtner