我正在处理仅将新数据添加到文本文件中的代码,然后让它运行,但随后又运行了一次,并产生了错误“ 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岁
切尔默10
纽霍尔20
您可能会有空白行,只需添加一项条件检查即可使其工作:
if data
如果在空白行上应用strip(),则为false。您可以检查是否在分隔线中使用逗号
for x in a_file.readlines():
data=x.strip()
if data and "," in data:
school,score=data.split(",")
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句