Reputation:
If I print a row in a CSV I get this result:
,,,,,,,some text,1781786000,
How can I check if an element row[2] has value?Is this correct if I check if element row[2] is empty:
if row[2] =! '':
print row[2]
or
if row[2] =! None:
print row[2]
How can I check if any of elements for row[0] till row[5] have no value so they are just ,, ?
let's suppose that in row[0:6] there's only one element that has a value others are empty, how can I make a condition that checks which element from row[0:6] has value?
Upvotes: 1
Views: 6274
Reputation: 1426
I'd do:
with open('csv_file.csv', 'r') as csv_file:
csv_reader = csv.reader(csv_file)
for row in csv_reader:
if not row[2]:
continue # this will skip to the next for loop iteration
# do your processing here
Upvotes: 0
Reputation: 8510
if you want to check if any element in the row have some value you can do
if any(row[0:6])
to know witch one you can do a filter and combined it with a enumerate to know its position like this
for i, value in filter(lambda pair: pair[1],enumerate(row[0:6])):
do something...
that is functional style of writhing this
for i,value in enumerate(row[0:6]):
if value:
do something ...
Upvotes: 0
Reputation: 1308
The "Pythonic" way of doing this is to simply say:
if row[2]:
print row[2]
This works because both None
and ''
would be interpreted as False-y values and the condition for the if
would not be satisfied.
Upvotes: 5