繁体   English   中英

python csv 读取列 function 没有给出正确的 Z78E6221F6393D1356681DB398F14CED6

[英]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.

我希望 function 以列表的形式从我的 csv 文件(包括标题)中打印出单列。

我对哪里出错感到非常困惑,并且非常感谢任何帮助。

提前感谢您的回复。

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

请输入列表中的值并返回列表:

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

在您的循环 function 中,您只返回您阅读的第一行。

所以,如果你想得到所有的线。 而不是在第一次阅读时返回column 您应该存储该值并立即返回所有存储的值。

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.

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