打开文件-无法将字符串转换为浮点:'-';-python
我的代码中出现以下错误:打开文件-无法将字符串转换为浮点:'-';-python,python,Python,我的代码中出现以下错误: File "D:/beverages.py", line XX, in <module> relst.append(Residents(float(value[0]),float(value[1]),str(value[2]))) ValueError: could not convert string to float: '-' 我不明白为什么该错误会抱怨单个-字符,它是否应该处理整个字段(带符号和数字)?您的问题在于: with ope
File "D:/beverages.py", line XX, in <module>
relst.append(Residents(float(value[0]),float(value[1]),str(value[2])))
ValueError: could not convert string to float: '-'
我不明白为什么该错误会抱怨单个
-
字符,它是否应该处理整个字段(带符号和数字)?您的问题在于:
with open("surveydata.txt") as file:
file1 = file.readline() # <-- read ONE line
relst = []
for line in file1 :
value = line.split()
relst.append(Residents(float(value[0]),float(value[1]),str(value[2])))
另外,特别是对于较大的文件,迭代文件本身要比使用.readlines()
高效得多,因为您不会将整个文件加载到内存中。因此,最终代码应如下所示:
with open("surveydata.txt") as file:
relst = []
for line in file:
value = line.split()
relst.append(Residents(float(value[0]),float(value[1]),str(value[2])))
请只添加相关代码。另外,您是否可以进行一些调试,以确定surveydata.txt中的哪一行是导致错误的原因?欢迎使用StackOverflow。请按照您创建此帐户时的建议,阅读并遵循帮助文档中的发布指南。适用于这里。在您发布MCVE代码并准确描述问题之前,我们无法有效地帮助您。请执行基本调试:在故障点之前打印出有问题的值。将它们追溯到以前的代码以确定问题。
with open("surveydata.txt") as file:
file1 = file.readlines()
relst = []
for line in file1:
value = line.split()
relst.append(Residents(float(value[0]),float(value[1]),str(value[2])))
with open("surveydata.txt") as file:
relst = []
for line in file:
value = line.split()
relst.append(Residents(float(value[0]),float(value[1]),str(value[2])))