简体   繁体   English

使用python csv reader忽略“空白”(未填充)行

[英]ignore “blank” (unfilled) row with python csv reader

everybody. 大家

I can't find a pythonic way to ignore "blank" lines in a CSV. 我找不到忽略CSV中“空白”行的pythonic方法。 I use quotes because I'm talking about lines that look like '','','','','' Here is a CSV (blank lines could be random): 我使用引号是因为我正在谈论的行看起来像是'','','','',''这是CSV(空白行可能是随机的):

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

Here is the code: 这是代码:

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

Here is similar questions that I've been reading, but different to this in particular: python csv reader ignore blank row 这是我一直在阅读的类似问题,但特别与此不同: python csv reader忽略空白行

You can use any to check if any column in the row contains data: 您可以使用any来检查该行中的任何列是否包含数据:

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

What about: 关于什么:

if len(rowdata) > 0:
    dataSet.append(rowdata)

Or am I missing a part of your question? 还是我错过了您的问题的一部分?

You can use the built-in function any : 您可以使用any内置函数:

for rowdata in reader:
    # how to check here?
    if not any(row):
        continue
    dataSet.append(rowdata)
 with open(fn, 'r') as csvfile: reader = csv.reader(csvfile) data = [row for row in reader if any(col for col in row)] 
  • open CSV file 打开CSV文件
  • instantiate csv.reader() object 实例化csv.reader()对象
  • use a list comprehension to: 使用列表推导来:
    • iterate over CSV rows 遍历CSV行
    • iterate over columns in the row 遍历行中的列
    • check if any column in the row has a value and if so, add to the list 检查行中是否有任何列具有值,如果有,则将其添加到列表中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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