Jackie
Jackie

Reputation: 11

python csv read column function not giving correct output

I am trying to read a single column in my csv data file with the following function, however when I run the function it only prints out the header instead of the whole column.

I want the function to print out a single column from my csv file (including the heading) in the form of a list.

I am very confused about where I am going wrong and would be very appreciative for any help.

thank you in advance for your response.

def read_column(filename, column:int):
    file = open ('data1.csv', 'r')
    for rows in csv_file:
        column = (rows.split(',')[0])
        return column

Upvotes: 0

Views: 75

Answers (2)

Fran Na Jaya
Fran Na Jaya

Reputation: 388

in your loop function you return only the first line you read.

So, if you want to get all the lines. Instead of return column at the first time you read it. You should store the value and return all the stored value at once.

def read_column(filename):
    file = open (filename, 'r')
    allLines = []
    for rows in csv_file:
        column = rows.split()
        allLines.append(column)
    
    # return all at once after read all lines.
    return allLines

print(read_column('data1.csv'))

Upvotes: 0

user9613901
user9613901

Reputation:

Please enter the values in the list and return the list:

def read_column(filename, column:int):
    file = open ('data1.csv', 'r')
    list=[]
    for rows in csv_file:
        column = (rows.split(',')[0])
        list.append(column)
    return list

Upvotes: 1

Related Questions