0

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

3 Answers 3

1

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)
Sign up to request clarification or add additional context in comments.

1 Comment

yes but the thing is I want it to do in a function body this is my question.
0

Becaues you use return print(x), you should return each lines of file. For example:

def read_data():
    filename = (r"\School_Project\Data\votes.csv")
    with open(filename) as csvfile:
        res = "\n".join(csvfile.readlines())
        print(res)


read_data()

1 Comment

Thanks I got your point!
0

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.

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.