You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python读取CSV文件时如何跳过表头行并解决ValueError整数转换报错

解决Python读取CSV时因表头无法转换整数的ValueError问题

这个报错ValueError: invalid literal for int() with base 10: 'temperature(F)'的根源很明确——你的代码把CSV的表头行当成了数据行来处理,试图把表头字符串temperature(F)转换成整数,这肯定会失败。下面给你两种简单有效的解决方法:

方法一:直接跳过表头行

最直接的方式就是在开始循环处理数据前,先读取并丢弃表头行。我们可以用next()函数来实现这一点:

arr = []
with open('D:\ml_learning\data-structures-algorithms-python-master\data_structures\4_HashTable_2_Collisions\Solution\nyc_weather.csv', 'r') as file:
    # 读取并跳过第一行(表头)
    next(file)
    for line in file:
        tokens = line.split(',')
        try:
            temperature = int(tokens[1])
            arr.append(temperature)
        except Exception as e:
            print('invalid temperature: ' + str(e))

next(file)会一次性读取文件的第一行,之后循环就从第二行(实际数据行)开始执行,再也不会碰到表头的字符串了。

方法二:使用Python内置的csv模块(推荐)

手动用split(',')处理CSV其实不太稳妥,比如遇到字段里包含逗号、换行符的情况会出错。Python自带的csv模块专门处理这类场景,而且能自动识别表头:

import csv

arr = []
with open('D:\ml_learning\data-structures-algorithms-python-master\data_structures\4_HashTable_2_Collisions\Solution\nyc_weather.csv', 'r') as file:
    # DictReader会自动把第一行作为表头,后续行以字典形式返回
    reader = csv.DictReader(file)
    for row in reader:
        try:
            # 直接通过表头字段名获取温度值
            temperature = int(row['temperature(F)'])
            arr.append(temperature)
        except Exception as e:
            print('invalid temperature: ' + str(e))

这种方式不仅避免了表头问题,还让代码更清晰——你可以直接通过字段名row['temperature(F)']获取数据,不用再靠索引tokens[1]来定位,可读性和可靠性都更高。

额外提示

如果你的CSV文件可能存在表头缺失或者格式不固定的情况,可以先读取第一行做个判断,比如检查tokens[1]是否等于'temperature(F)',再决定是否跳过。但对于固定格式的CSV,上面两种方法已经足够好用了。

内容的提问来源于stack exchange,提问作者Praveen Ezekiel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 11:38:14