0

I have a CSV file and I read the contents. I need to verify that every element of each row is not empty:

fname = row[0]
if fname is None:
    flag = -1
lname = row[1]
if lname is None:
    flag = -1
phone = row[2]
if phone is None:
    flag = -1
email = row[3]
if email is None:
    flag = -1
[...]

Is there a way to optimize this code? Is there a way to do something like this in Python:

fname = row[0] if None else flag = -1 ?
[...]

At the end I will check if flag is -1, I send an error notification (because this is a background task)

6
  • 1
    You could check if any of those values are None in a single statement at the end. Commented Nov 18, 2022 at 19:59
  • You can submit your answer please :) Thank you. Commented Nov 18, 2022 at 20:01
  • you can use pandas to check if any row of any column has null value check this stackoverflow.com/questions/71116935/… Commented Nov 18, 2022 at 20:06
  • 1
    if None in (fname, lname, phone, email): flag = -1 Commented Nov 18, 2022 at 20:53
  • @DennisWilliamson That works well if it's only 4 columns. Not so good if the csv file has 400, or it's variable. Commented Nov 19, 2022 at 0:05

2 Answers 2

1
if all([len(e) for e in row]):
    # Row is good
else:
    # Row is bad

We can't just do all(row) because there may be a non-empty but falsey value.

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

Comments

0

This could help you

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

Found it at https://www.folkstalk.com/tech/python-csv-row-index-is-empty-with-code-examples/

1 Comment

But what if row[5] is empty? That's the question, every field should be checked individually, my code actually works, I just wanted to optimize it a bit.

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.