InsideDarkWeb.com

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.

Stack Overflow Asked by cokola7775 on November 15, 2021

2 Answers

2 Answers

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

Answered by JD12 on November 15, 2021

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

Answered by Barmar on November 15, 2021

Add your own answers!

Related Questions

IndexError: tuple index out of range when running python 3.9.1

1  Asked on February 7, 2021 by ahmad-nur-hasybi

       

Azure Functions in VS Code

2  Asked on February 7, 2021 by nje

     

Python __hash__ performance for bulky data

0  Asked on February 7, 2021 by user14848693

   

error: failed to push some refs to ‘https://github.com/

8  Asked on February 7, 2021 by koeradoera

     

Specify type of data value in Vue (typescript)

1  Asked on February 6, 2021 by berco-beute

     

Show half of the other item on Owl Carousel

5  Asked on February 6, 2021 by domeniko

       

Python: How to write __repr__ when having __slots__

1  Asked on February 6, 2021 by sampleuser

       

Does AWS CDK support multiple languagues within a project?

1  Asked on February 5, 2021 by jason-vondersmith

   

Ask a Question

Get help from others!

© 2021 InsideDarkWeb.com. All rights reserved.