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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34192705/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 14:35:21  来源:igfitidea点击:

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

pythoncsv

提问by korakorakora

I have a CSV file that I'm reading in Python and I want the program to skip over the row if the first column is empty. How do I do this?

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

Right now I have:

现在我有:

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

How do I: 1) Check for empty cells in the CSV; and 2) tell the reader to skip the row?

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

Thanks guys.

谢谢你们。

采纳答案by Kit Fung

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

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

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

回答by Palak

You could use try and except.

您可以使用 try 和 except。

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

回答by Guillermo VELASCO

After hour of trying I was able to do it

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

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

回答by Apollo Data

Small adaptation of Kit Fung's answer:

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

回答by JoeyJoeJo22

I would assume if you len()it then would be zero i.e.

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

if not len(row[0])