Python读取燃油经济性数据文件时触发无效数据错误的求助
Python读取燃油经济性数据文件时触发无效数据错误的求助
别担心!刚接触文件读写的时候踩这种坑太正常了,我来帮你找出问题所在~
错误根源
你写入文件的每一行格式是这样的:
Model: 凯美瑞, Gallons used: 4.2
而你读取时直接用line.strip().split()按空格分割,会把整行拆成这样的列表:['Model:', '凯美瑞,', 'Gallons', 'used:', '4.2']
这时候你取data[1]是凯美瑞,,尝试把这个字符串转成float类型,自然会触发ValueError,也就是你看到的“invalid data”错误。
另外如果车型名称里带空格(比如“Tesla Model Y”),按空格分割还会把车型拆成多个元素,导致提取逻辑完全混乱。
修正后的读取代码
我们需要针对写入的格式来解析每一行,先用split(', ')把每行拆成“Model: xxx”和“Gallons used: yyy”两部分,再分别提取车型和油耗数值:
try: # Open the fuel economy data file for reading with open('fuel_economy_data.txt', 'r') as file: # Print the header row print("{:<20}{}".format("MODEL", "MPG")) print("-" * 30) # Loop through each line in the file for line in file: # 先按逗号加空格分割成两部分:["Model: 车型名", "Gallons used: 数值"] model_part, gallons_part = line.strip().split(', ') # 提取车型:去掉"Model: "前缀 model = model_part.split(': ')[1] # 提取油耗数值:去掉"Gallons used: "前缀并转成float gallons_used = float(gallons_part.split(': ')[1]) # Calculate the miles per gallon for the current car mpg = 100 / gallons_used # Print the model and its corresponding miles per gallon print("{:<20}{:.1f}".format(model, mpg)) except FileNotFoundError: print("Error: fuel_economy_data.txt not found.") except ValueError: print("Error: invalid data in fuel_economy_data.txt.") except Exception as e: print("Error:", e)
额外优化建议
为了避免后续再出现格式不匹配的问题,你可以在写入文件时用更规范的分隔符(比如制表符\t),这样读取时解析会更简单:
优化后的写入代码
try: with open('fuel_economy_data.txt', 'w') as f: # 先写入表头(可选,方便自己查看文件内容) f.write("Model\tGallons Used\n") for i in range(1, 6): car_model = input("Enter the model of car {} tested: ".format(i)) gallons_used = float(input("Enter the number of gallons used for car {} tested: ".format(i))) # 用制表符分隔数据,避免车型空格带来的问题 f.write("{}\t{}\n".format(car_model, gallons_used)) print("Data saved to fuel_economy_data.txt") except Exception as e: print("Error: ", e)
对应优化的读取代码
try: with open('fuel_economy_data.txt', 'r') as file: # 跳过表头行 next(file) print("{:<20}{}".format("MODEL", "MPG")) print("-" * 30) for line in file: # 按制表符分割,不用担心车型有空格 model, gallons_str = line.strip().split('\t') gallons_used = float(gallons_str) mpg = 100 / gallons_used print("{:<20}{:.1f}".format(model, mpg)) except FileNotFoundError: print("Error: fuel_economy_data.txt not found.") except ValueError: print("Error: invalid data in fuel_economy_data.txt.") except Exception as e: print("Error:", e)
这样不管车型名称有没有空格,都能正确解析啦~
备注:内容来源于stack exchange,提问作者squall1214
相关产品推荐
相关产品推荐

