Python如何跳过CSV文件中首列为空或非数值的行
Python过滤CSV首列非数字/空行方案
可以直接用Python内置的csv模块实现,不需要安装第三方依赖,处理逻辑如下:
完整实现代码
import csv # 替换为你本地实际的输入、输出文件路径 input_file = "source.csv" output_file = "filtered_result.csv" with open(input_file, "r", encoding="utf-8") as f_in, open(output_file, "w", encoding="utf-8", newline="") as f_out: csv_reader = csv.reader(f_in) csv_writer = csv.writer(f_out) for row in csv_reader: # 处理空行、首列去前后空白 first_col = row[0].strip() if len(row) > 0 else "" # 首列非空且为纯数字则保留 if first_col and first_col.isdigit(): csv_writer.writerow(row)
逻辑说明
- 采用内置csv模块读写文件,避免手动切割字符串导致的格式适配问题
- 对首列先做
strip()处理,可过滤首列为全空白字符的异常行 isdigit()方法直接判断字符串是否全部由数字组成,刚好匹配需求中的「非数值」过滤规则- 运行完成后输出的
filtered_result.csv就是你要的结果
如果你的场景下首列支持带小数点的数值,可自定义数值判断函数替换原有判断逻辑即可:
def is_numeric(val: str) -> bool: try: float(val) return True except ValueError: return False # 原有判断改为 if first_col and is_numeric(first_col):
内容的提问来源于stack exchange,提问作者Ashu
相关产品推荐
相关产品推荐

