我正在编写这段代码,它只是将新数据添加到文本文件中,我让它工作了,但后来我再次运行它,它产生了错误“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
最佳答案
您可能有空行,只需添加一个条件检查即可使其工作:
如果在空行上应用 strip(),if data
将为 false。您可以检查剥离行中是否有逗号
for x in a_file.readlines():
data=x.strip()
if data and "," in data:
school,score=data.split(",")
关于python - ValueError : not enough values to unpack (expected 2, 得到 1) 但我提供了 2 个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47561961/