繁体   English   中英

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

[英]Python: How to check if cell in CSV file is empty?

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

现在我有:

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

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

谢谢你们。

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

参考: 如何以 Pythonic 的方式检测 CSV 文件中的缺失字段?

您可以使用 try 和 except。

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

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

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

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

我会假设如果你len()那么它将为零,即

if not len(row[0])

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

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

暂无
暂无

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

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