如果python中任何行中的任何单元格为空(或为空),如何删除整行

时间:2017-05-15 11:50:51

标签: python-3.x

我有以下CSV数据:

AAB  BT  2   5  5
YUT  HYT 89  52 3
YHT  JU  25  63 2

在第3行(和第4行)中,第一列(和第2列)元素为空,因此删除整个第3行(和第4行)。同样,整个第5行为空,也删除整个第5行。 我想要的输出应该是:

import csv
input(r'\\input.csv','r')
output=open(r'Outpur.csv','w',newline="")
writer= csv.writer(output)
for row in csv.reader(input):
    if any(field.strip() for field in row):
        writer.writerrow(row)
input.close()
output.close()

我使用以下代码,但它没有删除。

{{1}}

2 个答案:

答案 0 :(得分:1)

首先,请参阅@RomanPerekhrest对原始问题的评论。此答案假定您打算删除示例中的第6行数据。

看起来像你的代码行:

if any(field.strip() for field in row):
如果数据行中的任何字段包含条目,则

返回true。

我怀疑你想要的东西(如果我理解你的要求正确的话)是,如果行中所有的字段包含一个条目,那么就要保留数据行。因此,请尝试更改您的代码以使用:

if all(field.strip() for field in row):

另外,检查调试器以确保代码通过将其拆分为CSV文件中的每个逗号来正确地对行进行标记。 如果field.strip()抛出异常(特别是对于空字段),则可能需要尝试使用字符串长度测试。类似的东西:

if all(len(str(field).strip()) > 0 for field in row):

答案 1 :(得分:0)

    #the following line reads the entire data from your csv file
    #list contains list of every fields that are seperated by comma in your 
    csv file
    #of every line
    #

    data_list=[[s.strip() for s in lines.split(',')] for lines in 
    open('c:/python34/yourcsv.csv')]


    #now you can filter out any list inside your data list
    #according to your choice
    #such as lists whose length are less than it should be
    # lets try it


    filtered=[item for item in data_list if not(len(item)<5)]



    #now you can overwrite the existing file or simply save it to new file
    #and do whatever you want
    for item in filtered:
        print(item)
相关问题