简体   繁体   中英

Cannot return list elements from Python function

I have a function, table() , that reads a csv file and returns the rows in individual lists. I want to map these lists to create a dictionary, with field headers being the keys and the underlying rows being the values. I cannot seem to do this however. When I try to call only the first element within the list of lists I created from the function ( l ) in the command prompt, it returns all the lists up to 'N', the first letter in the word 'None', despite me breaking (return) if reader is None. When I do the same with a sys.stdout to a text file, it does the same, but the 'N' is replaced with <type 'list'> . Does anyone know what I'm doing wrong, and how I can go about creating a dictionary (or a list of columns, for that matter) from a CSV file given my table() function?

import csv

def table():
    with open('C:\\Python27\\test.csv', 'rb') as f:
        reader = csv.reader(f)
        for row in reader:
            print row
        if reader is None:
            return

l = list(str(table()))
keys = l[0]
print keys

Output text file:

['Field1', 'Field2', 'Field3', 'Field4']
['a', '1', 'I', 'access']
['b', '2', 'II', 'accessing\n']
['c', '3', 'III', 'accommodation']
['d', '4', 'IIII', 'basically']
<type 'list'>

More pythonically

def table():
    with open('C:\\Python27\\test.csv', 'rb') as f:
        reader = csv.reader(f)
        for row in reader:
            yield row

You don't actually return anything from the table function. Try it like this:

def table():
    with open('C:\\Python27\\test.csv', 'rb') as f:
        lines = []
        reader = csv.reader(f)
        if reader:
            for row in reader:
                lines.append(row)
            return lines
        else:
            return []

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM