Python:如何检查CSV文件中的单元格是否为空?

时间:2015-12-10 02:27:25

标签: python csv

我有一个CSV文件,我在Python中阅读,如果第一列为空,我希望程序跳过该行。我该怎么做?

现在我有:

with open('testdata1.csv', 'rU') as csvfile:
        csvreader = csv.reader(csvfile)
        for row in csvreader:
            if row[0] = null:
                #?????

我如何:1)检查CSV中的空单元格; 2)告诉读者跳过这一行?

谢谢你们。

6 个答案:

答案 0 :(得分:8)

with open('testdata1.csv', 'r') as csvfile:
    csvreader = csv.reader(csvfile)
    for row in csvreader:
        print(row)
        if row[0] in (None, ""):
             print("12")

参考: How do I detect missing fields in a CSV file in a Pythonic way?

答案 1 :(得分:2)

你可以使用try和except。

for row in csvreader:
        try:
               #your code for cells which aren't empty
        except:
               #your code for empty cells

答案 2 :(得分:0)

经过一个小时的尝试,我能够做到

while act_tab.cell(row=i, column=1).value is not None:
    ...

答案 3 :(得分:0)

Kit Fung答案的小改编:

with open('testdata1.csv', 'r') as csv_file:
csv_reader = csv.reader(csv_file)
for row in csv_reader:
    if not row[0]:
         continue  # this will skip to the next for loop iteration
    # do your processing here

答案 4 :(得分:0)

我假设如果您len()则为零,即

if not len(row[0])

答案 5 :(得分:0)

我尝试了如果您打印并清空行并且它返回[](空括号)...会发生什么情况,所以只需检查一下即可。

with open('testdata1.csv', 'rU') as csvfile:
    csvreader = csv.reader(csvfile)
    for row in csvreader:
        if row == []:
            continue
        #do stuff normally