ValueError:没有足够的值来解压缩(预期2,得到1)但是我提供了2个值(ValueError: not enough values to unpack (expected 2, got 1)

编程入门 行业动态 更新时间:2024-10-27 09:32:43
ValueError:没有足够的值来解压缩(预期2,得到1)但是我提供了2个值(ValueError: not enough values to unpack (expected 2, got 1) BUT i provide 2 values)

我正在研究这个代码,只是简单地将新数据添加到文本文件中,我让它工作但是我再次运行它并且它产生了错误“ValueError:没有足够的值来解包(预期2,得到1)”。 我知道这个错误意味着什么,我似乎提供了两个值? 我一定错过了一些错误的东西?

它产生错误的代码:

schoolnames=[] scores=[] with open("Cdrive.txt","r")as a_file: for x in a_file.readlines(): data=x.strip() #Im aware i could just use data, but i use X to try fix the error, of course this didnt work print(data) school,score=data.split(",") #The error is produced here schoolnames.append(school) scores.append(score)

我的文本文件如下所示(文本文件中每个数据位之间没有行):

SJP,15

chelmer,10

纽荷尔,20

Im working on this code that simply adds new data into a text file, and i had it working but then i ran it once more and it produced the errer "ValueError: not enough values to unpack (expected 2, got 1)". I know what this error means its just that i seem to provide two values? i must be missing something thats wrong?

The code where it produces an error:

schoolnames=[] scores=[] with open("Cdrive.txt","r")as a_file: for x in a_file.readlines(): data=x.strip() #Im aware i could just use data, but i use X to try fix the error, of course this didnt work print(data) school,score=data.split(",") #The error is produced here schoolnames.append(school) scores.append(score)

My text file looks like this (there are no lines between each bit of data in the text file):

sjp,15

chelmer,10

newhall,20

最满意答案

你可能有空行,你可以让它工作只需添加一个条件检查:

if data在空行上应用strip(), if data为false。 你可以检查被剥离的行中是否有逗号

for x in a_file.readlines(): data=x.strip() if data and "," in data: school,score=data.split(",")

You may have blank lines, you can make it work just add one condition checking:

if data would be false if you apply strip() on a blank line. you can check whether comma in the stripped line

for x in a_file.readlines(): data=x.strip() if data and "," in data: school,score=data.split(",")

更多推荐

本文发布于:2023-08-03 15:35:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1393302.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:解压缩   没有足够   但是我   ValueError   provide

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!