首页 > 解决方案 > 如何从csv文件python中跳过非数字行

问题描述

我有示例 csv 文件,其字符串值如下:

1234, san@mail, IN, 001
, ram@mail, IN, 003
1235, john@mail, IN, 004 
san-ba, luios@mail, IN, 005 
undefined, thomas@mail, IN, 006

我需要跳过文件中 row[0] 中具有空且非数字的行。

预期结果:

1234, san@mail, IN, 001
1235, john@mail, IN, 004 

标签: python

解决方案


您可以尝试将值转换为浮点数,如果失败,则跳过它:

for row in data:
    first_val = row[0]
    try:
        float(first_val)
    except ValueError:
        continue
    # here you use the row, knowing the first value is numerical
    print("this row has a numerical value in index 0")

推荐阅读