Python写入CSV遇float错误求助:实现表头式行程数据存储
问题解决:写入CSV时的float错误及重复表头问题
错误原因分析
writerows使用错误:csv.writer.writerows()要求传入多行数据的集合(比如列表套列表),而你传入的是单行数据的列表[miles, gallons, mpg]。程序会把每个float值当作单独的行去解析,但float类型无法被迭代,因此触发TypeError。- 重复覆盖表头:每次调用
save_data都用'w'模式打开文件写入表头,这会清空之前的文件内容,导致多次输入时表头重复、历史数据丢失。
修正后的代码
import csv import os FILENAME = "trip.csv" def save_data(miles, gallons, mpg): header = ["Distance", "Gallons", "MPG"] data = [miles, gallons, mpg] # 检查文件是否存在,不存在则写入表头 file_exists = os.path.isfile(FILENAME) with open(FILENAME, 'a', newline="") as file: writer = csv.writer(file) if not file_exists: writer.writerow(header) # 用writerow写入单行数据,而非writerows writer.writerow(data) def display_title(): print("The Miles Per Gallon program.\n") def calculate_totals(miles, gallons, cost): mpg = miles / gallons cost_per_mile = (gallons * cost) / miles # 修正每英里成本计算逻辑 total_fuel_cost = gallons * cost display_data(mpg, cost_per_mile, total_fuel_cost, gallons, miles) def display_data(mpg, cost_per_mile, total_fuel_cost, gallons, miles): print() print(f"MPG on this trip is {mpg:.2f}") # 修正描述,MPG是每加仑行驶英里数 print(f"Cost per mile was ${cost_per_mile:.2f}") print(f"Total fuel spent was ${total_fuel_cost:.2f}") print() save_data(miles, gallons, mpg) def main(): display_title() choice = "y" while choice.lower() == "y": miles = float(input("Enter miles driven: ")) gallons = float(input("Enter gallons used: ")) cost = float(input("Enter cost per gallon: ")) calculate_totals(miles, gallons, cost) choice = input("Do you wish to enter a new entry: y/n ") if __name__ == "__main__": main()
关键修改说明
- 替换
writerows为writerow:单行数据用writerow(),多行数据才用writerows()(比如传入[[100, 5, 20], [200, 10, 20]])。 - 添加文件存在性检查:用
os.path.isfile()判断文件是否存在,仅在文件首次创建时写入表头,避免重复覆盖。 - 修正逻辑与输出格式:修复了
cost_per_mile的计算错误,同时优化了输出的格式和描述,让结果更易读。
效果验证
运行程序后,输入多次行程数据,trip.csv会生成如下格式的内容:
Distance,Gallons,MPG 100.0,5.0,20.0 200.0,10.0,20.0
内容的提问来源于stack exchange,提问作者Timothy Easter
相关产品推荐
相关产品推荐

