Same lines of codes have different output with and without function, i don't understand why

Question:

When I use def to build a function for reading from a csv file and printing out all of its lines, it only prints first line of it

def reader(x):
    with open(x,'r') as f:
       csv_reader = csv.reader(f)
       for line in csv_reader:
          return line

print(reader('scores.csv'))

output: ['mandana', '5', '7', '3', '15']

But when I use the same lines without building a function it works well. I’m new to python so I don’t understand what exactly happening here and what did I do wrong here, same thing happened to me before only when I use for loop

Asked By: pouyan

||

Answers:

When the function reaches return, it returns a value and stops working. In your case, the function should print the value itself, and return nothing. Try this:

def reader(x):
    with open(x,'r') as f:
       csv_reader = csv.reader(f)
       for line in csv_reader:
          print(line)

reader('scores.csv')
Answered By: Vladislav Sokolov

As others have explained, your primary issue is that you have the return statement inside your loop. Therefore, on the first iteration of said loop, your function will return. There are two ways you can fix this code.

First, you can coalesce your data into a list and return that:

def reader(x):
    with open(x,'r') as f:
       csv_reader = csv.reader(f)
       return csv_reader

for line in reader('scores.csv'):
    print(line)

The advantage here is that you can handle all the data at once and then close the file. Alternatively, if you want to handle each line separately, you can turn the function into a generator:

def reader(x):
    with open(x,'r') as f:
       csv_reader = csv.reader(f)
       for line in csv_reader:
           yield line

for line in reader('scores.csv'):
   print(line)

This allows you to interpret each line of the CSV, operate on it, and return it to the caller, thus creating a data pipeline from your file through your application. Done properly, this code can run more efficiently.

Answered By: Woody1193
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.