0

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
1
  • your question says prints but in your function you are returning. please add more details. Commented Dec 30, 2021 at 14:10

2 Answers 2

1

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

Comments

0

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'))

2 Comments

thank you for your response however, when I run this it still only returns the header of my csv file column
@Jackie, I have not paying attention to your code a little, you need to change how you split each line. use rows.split() instead of (rows.split(',')[0]). I have fix the code above

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.