我正在研究这个代码,只是简单地将新数据添加到文本文件中,我让它工作但是我再次运行它并且它产生了错误“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(",")更多推荐
发布评论