猿问

尝试将文本文件放入数组时,python 值错误预期 2 收到一个

我试图获取一些代码,该代码将查看一个文本文件并将行拆分为 2 个变量,但是当我运行此代码时,我收到错误 ValueError: 没有足够的值来解包(预期 2,得到 1), 代码是:


x=0

f = open("scores.txt","a")    

f.write("\n")    

f.write("andrew:78")    

f.write("\n")    

f.write("karen:64")    

f.close    

f = open("scores.txt","r")        

a,b = ("karen:67").split(":")    

print (a)    

print(b)





scores = [[],[]]

while 0 != 1 :

    line=(f.readline(x))

    a,b = (line).split(":")


    scores[0] = a    

    scores[1]=b

这是文本文件,提前致谢


慕尼黑的夜晚无繁华
浏览 107回答 3
3回答

潇湘沐

这 line=(f.readline(x))是类似的东西 (["content of file"]),即它是元组内列表中的文件内容。您需要将其定义的大小x从 0 更改为某个值,或者不使用它。即 fromline = (f.readline(x))到line = f.readline()现在将是一个字符串。现在您可以对字符串对象使用拆分操作。改成a, b = (line).split(':')_a, b = line.split(':')所以新的代码将是# opening/cretaing a file and adding datawith open("scores.txt", 'a') as f:&nbsp; &nbsp;&nbsp; &nbsp; f.write("\n")&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; f.write("andrew:78")&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; f.write("\n")&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; f.write("karen:64")&nbsp; &nbsp;&nbsp;# creating a dictionary to save data of name and score respectivelyscores = {'name':[], 'score':[]}# again opening the file in read modewith open("scores.txt", 'r') as f:&nbsp; &nbsp; data = f.readlines() # reading all line in file at single time&nbsp; &nbsp; for each_line in data:&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; if line.split(':'): # checking if each line has format <name>:<score> or not, if yes then add that data to scores dict&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; name, score = line.split(':')&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; scores['name'].append(name)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; scores['score'].append(score)# seeing the resultprint(scores)

慕森卡

这段代码能达到你想要的效果吗?with open("scores.txt", "a") as f:&nbsp; &nbsp; f.write(&nbsp; &nbsp; &nbsp; &nbsp; "\nandrew:78"&nbsp; &nbsp; &nbsp; &nbsp; "\nkaren:64"&nbsp; &nbsp; )scores = []with open("scores.txt", "r") as f:&nbsp; &nbsp; lines = f.readlines()&nbsp; &nbsp; for line in lines:&nbsp; &nbsp; &nbsp; &nbsp; if ":" in line:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; a, b = (line).split(":")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; scores.append({a: b})您可能遇到错误,因为某些行(空白行)没有“:”,因此该行只是一个字符串,您试图将其解压缩为两个变量。

HUH函数

它会在换行符 '\n' 之前打印出一个空字符 '' - 我认为你想要的是这样的:lines = f.read().splitlines()#This will only get the value for one linescores[0], scores[1] = lines[0].split(':')#Or to get both lines:i=0for line in f.read().splitlines():&nbsp; &nbsp; scores[i][0], scores[i][1] = line.split(':')&nbsp; &nbsp; i += 1
随时随地看视频慕课网APP

相关分类

Python
我要回答