cokola7775
cokola7775

Reputation: 23

Python - How do you restart a for loop?

I am quite new to python and I have seen similar questions being answered but I had a lot of trouble understanding them so I am creating a new question.

I will try to give as much context and code as needed.

So I am trying to search a .csv file for a string/number (I am only searching for it in the first column) and if I find it I will have it grab the entire row of where the string/number is situated at.

(import csv was included)

input_string = input()
input_string_2 = input()

def search(x):          
    for row in (the .csv file):
        if x == row[0]:
            print (row)
            return row

output_array = search(input_string)
output_array_2 = search(input_string_2)

This seem to work with one input. But if I try with multiple inputs it only goes through the list once meaning sometimes I will not get the result for the second search. I am asking if anyone knows how to make it start over every time the function the called. Thanks in advance.

Just a note I did not get any errors when I executed this so if there is some obvious spelling mistake it is probably not the problem.

Edit: The solution that was posted might not be broad enough to address the question in other situations.

Upvotes: 2

Views: 69

Answers (2)

JD12
JD12

Reputation: 106

Not sure if this was what you were looking for:

def search(x):
    y = []
    for row in csv_file:
        if x == row[0]:
            print(row)
            y.append(row)
    return y

Upvotes: 0

Barmar
Barmar

Reputation: 780808

You need to seek back to the beginning of the file, otherwise there's nothing left to read.

def search(x):
    csv_file.seek(0)
    for row in csv_file:
        if x == row[0]:
            print(row)
            return row

Upvotes: 2

Related Questions