12

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.

6 Answers 6

21
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?

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

7 Comments

Great! What about skipping the row (as in not reading it, and moving to the next)?
if row[0] in (None, ""): continue
if row[0] in (None, "") can be more Pythonically written as if not row[0]
@jamylak if not row[0] will not mean the same as if row[0] in (None, "") in case of 0 as the value in the cell of a CSV.
@YDF That would be "0" not 0
|
3

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

Comments

1

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
   

1 Comment

Also instead of continue an else statement is possible...
0

After hour of trying I was able to do it

while act_tab.cell(row=i, column=1).value is not None:
    ...

1 Comment

kindly consider adding more information to your answer
0

Small adaptation of Kit Fung's answer:

with open('testdata1.csv', 'r') as csv_file:
csv_reader = csv.reader(csv_file)
for row in csv_reader:
    if not row[0]:
         continue  # this will skip to the next for loop iteration
    # do your processing here

1 Comment

if not row[0] will not account the same for 0 as the value in the cell of a CSV then for something like None or "".
0

I would assume if you len() it then would be zero i.e.

if not len(row[0])

Comments

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.