1

My objective is to search a small csv file (one column, a few hundred rows) for a value. The rows in the csv are all numbers. Here is my attempt:

import csv

#read csv file
csv_reader = csv.reader(open('test.csv', 'rU'))

length_list = len(list(csv_reader))
value = []

for line in csv_reader:
    value.append(line) #transfer contents of csv to list

def find_voucher(input_voucher, counter):
    while counter < length_list:
        check_voucher = input_voucher in value[counter]
        if check_voucher == True:
            print "TRUE"
        else:
            print "FALSE"
    counter = counter + 1
find_voucher(1000,1)

When I run the script I get this error:

check_voucher = input_voucher in value[counter]
IndexError: list index out of range

2 Answers 2

4

csv.reader is an iterator -- after you go through it once, it's empty, unlike a list. You use it up when you do

length_list = len(list(csv_reader))

There are a number of ways you could simplify your program, but if you just do

length_list = len(value)

after the for loop instead of trying to find the length first, it should work.

An example of how you could simplify your program:

def find_voucher(input_voucher, filename):
    with open(filename, 'rU') as f:
        return ("%s\n" % input_voucher) in f

print find_voucher(1000, 'test.csv')
Sign up to request clarification or add additional context in comments.

2 Comments

First things first: your simplified script worked perfectly. I am still very new to python and I have not delved into "with".
@BrandonDorris In this case, the with statement just automatically closes the file. The main point of that example was the return part, showing you how you can test if a line exists in a file very easily. There are lots of objects in Python that are iterators, so you're likely to hit the problem of consuming them accidentally again.
0

I'd do something like this:

# value we're looking for
desired_value = 1000

# read csv file
csv_reader = csv.reader(open('test.csv', 'rU'))

# loop through csv file
for line_number, line in enumerate(csv_reader):
    # catch errors in converting to float
    try:
        # if desired matches first value on line
        if desired_value == float(line[0]): 
            # print line number and value
            print line_number, line[0]
    except ValueError as e:
        continue

This looks through the CSV once, converts the first value on each line to a float, and then if the converted float matches the desired_value, print the line number and value matched.

Test.csv:

10
20
1000
1500

Output:

2 1000

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.