Skip to main content
 首页 » 编程设计

python之使用 python csv 阅读器忽略 "blank"(未填充)行

2025年05月04日14powertoolsteam

大家。

我找不到忽略 CSV 中“空白”行的 pythonic 方法。我使用引号是因为我在谈论看起来像 '','','','','' 的行 这是一个 CSV(空行可以是随机的):

id,name,age 
1,alex,22 
3,tiff,42 
,, 
,, 
4,john,24 

代码如下:

def getDataFromCsv(path): 
    dataSet = [] 
    with open(unicode(path), 'r') as stream: 
        reader = csv.reader(stream, delimiter=',') 
        reader.next() # ignoring header 
        for rowdata in reader: 
            # how to check here? 
            dataSet.append(rowdata) 
    return dataSet 

这是我一直在阅读的类似问题,但与此特别不同: python csv reader ignore blank row

请您参考如下方法:

您可以使用 any检查行中是否有任何列包含数据:

for rowdata in reader: 
    # how to check here? 
    if any(x.strip() for x in rowdata): 
        dataSet.append(rowdata)