Pages

Saturday, June 9, 2012

Python: Find row in CSV file with a specified value in given column


def FindRowInCSV(file_name, column_position, the_value):
'''Returns the first row# where the value is present in the specified
column of the provided CSV file'''
f = open(file_name, 'rt')
try:
reader = csv.reader(f)
i = 1
for row in reader:
if str(row[column_position]) == str(the_value):
return i
i += 1
except:
logger.debug ('Error Reading CSV file: ' + str(sys.exc_info()[1]))
finally:
f.close()
return -1

No comments:

Post a Comment

Please write your comments and suggestions