如何在Python中忽略CSV文件中的空值并继续执行
没问题,我来帮你完善这段代码,实现忽略CSV中空值的功能!
解决CSV合并时忽略空值的问题
首先先把你未完成的原代码补全(跳过表头+逐行合并对应列),方便你对比修改点:
import csv res = [] with open('csvexample.csv') as f, open('csvexample1.csv') as a: reader = csv.reader(f) reader1 = csv.reader(a) # 跳过两个文件的表头 next(reader) next(reader1) # 逐行读取并合并指定列 for row, row1 in zip(reader, reader1): res.append((row[0], row1[1]))
接下来我们添加空值判断逻辑,确保遇到空列/空行时自动跳过,不影响后续执行:
import csv res = [] with open('csvexample.csv') as f, open('csvexample1.csv') as a: reader = csv.reader(f) reader1 = csv.reader(a) # 跳过表头 next(reader) next(reader1) for row, row1 in zip(reader, reader1): # 提取目标列并清理格式(去除前后空白、CSV里的单引号) id_col = row[0].strip().strip("'") if row else "" month_col = row1[1].strip().strip("'") if row1 else "" # 只有当两列都不为空时,才加入结果列表 if id_col and month_col: res.append((id_col, month_col))
关键逻辑说明:
- 空白处理:用
strip()去除单元格前后的空格、换行符,避免把“看似空的空白字符串”误判为有效值 - 单引号清理:
strip("'")是针对你CSV里带单引号的内容(比如'Feb'),如果不需要去除可以删掉这部分 - 空值判断:
if id_col and month_col确保只有两列都有实际内容时,才会把数据加入res - 异常防护:
if row else ""避免某一行完全为空时,访问索引row[0]或row1[1]报错
这样修改后,不管是单元格为空、仅含空白字符,还是整行无内容,代码都会自动跳过这些无效行,继续执行后续的合并操作。
内容的提问来源于stack exchange,提问作者Nienke Luirink
相关产品推荐
相关产品推荐

