kirkofthefleet
kirkofthefleet

Reputation: 21

How do you return multiple lines using a Python function?

I am working on a script that reads through a csv file and returns some information. I am VERY new to python so I may be taking the wrong approach. All I want this part of the script to do is read the file and return the value that is in postion 6 of each row into a list. When I run the function with print, it will print out postion 6 of each row as expected. However, when I change print to return, it only prints position 6 of the first line. I need return to work, because I want to use the result in the next part of the script.

import csv

def gatherQueries():
    queries = []
    with open('AMS.csv') as ams_file:
        csv_reader = csv.reader(ams_file, delimiter=',')
        for row in csv_reader:
            #return row[6]
            print row[6]

gatherQueries()

The code above will show the information I want, but unless I write it to a file and then read that file into the next part of the script (which is cludgy IMO), I have no way of making use of the output. However, when I use return instead of print, I only get the first row:

import csv

def gatherQueries():
    queries = []
    with open('AMS.csv') as ams_file:
        csv_reader = csv.reader(ams_file, delimiter=',')
        for row in csv_reader:
            return row[6]
            #print row[6]

search = gatherQueries()
print search

Upvotes: 1

Views: 138

Answers (3)

Naman
Naman

Reputation: 306

Try this

import csv

def gatherQueries():
    queries = []
    with open('AMS.csv') as ams_file:
        csv_reader = csv.reader(ams_file, delimiter=',')
        for row in csv_reader:
            queries.append(row[6])
    return queries 

search = gatherQueries()
print search

Upvotes: 0

bbear13
bbear13

Reputation: 22

You need to append results to the list and return the list

def gatherQueries():
    queries = []
    with open('AMS.csv') as ams_file:
        csv_reader = csv.reader(ams_file, delimiter=',')
        for row in csv_reader:
            queries.append(row[6])
    return queries
    
search = gatherQueries()
print(search)

Upvotes: 0

Tim Roberts
Tim Roberts

Reputation: 54708

You almost had it.

import csv

def gatherQueries():
    queries = []
    with open('AMS.csv') as ams_file:
        csv_reader = csv.reader(ams_file, delimiter=',')
        for row in csv_reader:
            queries.append( row[6] )
    return queries

search = gatherQueries()
print search

Upvotes: 2

Related Questions