Home > Enterprise >  python for loop not working inside a function body
python for loop not working inside a function body

Time:10-11

This is my code-

def read_data():
    filename=(r"\School_Project\Data\votes.csv")
    with open(filename) as csvfile:
        for data in csvfile: #here data 
            csvfile.seek(0)
            for x in csvfile.readlines():
                return print(x)

read_data()

Here the data is not iterating i.e. for loop isnt working well inside function body and cannot print all the values in the file only 1st line is being printed Please help me out with this error

CodePudding user response:

You cannot iterate through a csv file like this. You will need a library like csv or pandas. See for example:

import csv

filename = (r"\School_Project\Data\votes.csv")

with open(filename, 'r') as csvfile:
    datareader = csv.reader(csvfile)
    for row in datareader:
        print(row)

CodePudding user response:

Because you use return there which ends the function -- and thus the loop as well -- after the first iteration.

Also why do you need to iterate over csvfile? .readlines() already does that for you and gives you back a list of all the lines in the file.

Finally, as @GrowingWings mentioned, avoid processing CSV files manually; use csv or pandas instead.

  • Related