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

Python处理CSV时字符串转int报错:跳过表头与十进制字符串转换方案

解决方案

疑问1:跳过表头行处理

你读取的contents列表中索引为0的元素就是表头行,只需要调整遍历范围从索引1开始即可,同时建议先把表头写入输出的CSV文件,保证输出文件结构完整。

疑问2:十进制格式字符串转int

对于0.0这类带小数点的字符串,无法直接强制转为int类型,需要先转为float类型再转int,示例写法:int(float(contents[row][6])),即可避免格式转换报错。

其他代码问题修正

你原有代码中死亡数累加逻辑存在错误:deaths += deaths + int_deaths 会导致数值重复计算,正确写法为deaths += int_deaths

修正后的完整代码

import csv

input_file = 'all.csv'
state = input()
date = input() # date format m/d/yyyy
output_file = state + '.csv'


def number_of_cases_deaths_by_date(input_file, output_file, state, date):
    with open(input_file, 'r') as infile:
        contents = infile.readlines()
        
        with open(output_file, 'w', newline='') as outfile:
            writer = csv.writer(outfile)
        
            for row in range(len(contents)):
                contents[row] = contents[row].split(',')
                contents[row][-1] = contents[row][-1].strip('\n')
            
            # 先写入表头到输出文件
            writer.writerow(contents[0])
            
            cases = 0
            deaths = 0
            
            # 从第1行开始遍历,跳过表头
            for row in range(1, len(contents)):
                if contents[row][3] == state and contents[row][1] == date:
                    writer.writerow(contents[row])
                    # 先转float再转int处理十进制字符串
                    int_cases = int(float(contents[row][5]))
                    cases += int_cases
                    int_deaths = int(float(contents[row][6]))
                    deaths += int_deaths
            return (cases, deaths)
                    
                
data = number_of_cases_deaths_by_date(input_file, output_file, state, date)
print(data)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 23:45:08