I wish to select a specific row and column from a CSV file in python. If the value is blank, I want to perform one action, and if the value is not blank, I want to perform another action.
I think the code should look something like this:
inputFile = 'example.csv'
reader = csv.reader(inputFile, 'rb')
for row in reader:
if row[5][6] == '': ==> (I mean select value the 5th row and 6th column)
(do this)
else:
(do that)
Any help or guidance on this topic would be helpful -- I've done a similar task using lists; however, since the CSV file is raw, I don't know what to do.
When you think CSV, think pandas.
import pandas as pd
df = pd.read_csv('path/to/csv')
if df.iloc[5, 6]:
# do stuff
else
# do some other stuff
Both inspectorG4dget and Oscar Lopez have the right idea, but there are flaws in their solutions. Thus, I present my own.
The general idea is that csv.reader is just a special file object that automatically splits things on commas. Treat it like any other file object. If you want the nth line, iterate until you hit the nth line.
with open('inputFile', rb) as f:
reader = csv.reader(f)
for i, l in enumerate(reader):
if i==5:
try:
print l[6]
except IndexError:
print "Nothing here!"
A few notes:
with
block so that the file is safely closed on the completion of this code. You can always call file.close
yourself, but this is better practice.try...except
because, well, there might not be a 6th column. Better safe than sorry.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With