簡體   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