[英]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 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.我希望 function 以列表的形式从我的 csv 文件(包括标题)中打印出单列。
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
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
in your loop function you return only the first line you read.在您的循环 function 中,您只返回您阅读的第一行。
So, if you want to get all the lines.所以,如果你想得到所有的线。 Instead of return
column
at the first time you read it.而不是在第一次阅读时返回
column
。 You should store the value and return all the stored value at once.您应该存储该值并立即返回所有存储的值。
def read_column(filename, column:int):
file = open ('data1.csv', 'r')
allLines = []
for rows in csv_file:
column = (rows.split(',')[0])
allLines.append(column)
# return all at once after read all lines.
return allLines
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.