with open file无法将字符串转换为float:“”python

2024-06-16 10:32:23 发布

您现在位置: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: '-'

代码如下:

^{pr2}$

surveydata.txt文件包含:

-3.043296714578294 -1.8118219429417417  Pepsi
-2.934406412013738 -3.2258867426312845  Pepsi
3.750989559940674 0.6649706751908528  Coke
4.453731061614226 1.1760692786505302  Coke
-3.3141673450571307 2.7471154522861942  Coke
-1.5611978286453065 0.9748847584776836  Coke
-0.6446977323819532 -1.4945077535804119  Pepsi
-4.280039869935868 3.2099331922984433  Coke

我不明白为什么错误会抱怨一个-字符,它不应该处理整个字段(带有符号数字)吗?在


Tags: 代码inpyvalue错误linefloatfile
1条回答
网友
1楼 · 发布于 2024-06-16 10:32:23

你的问题在于:

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])))

file1变量只包含文件的一行(作为字符串),而不是每一行(作为字符串的集合)。这意味着for line in file1将迭代字符串中的每个字符,而不是集合中的每个,这就是它抱怨单个的-字符的原因。在

所以您应该将file1 = file.readline()更改为file1 = file.readlines(),以读取所有行:

^{pr2}$

另外,特别是对于较大的文件,迭代文件本身比使用.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])))

相关问题 更多 >