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

python value error expected 2 recieved one when trying to put a text file into an array

我正在尝试获取一些代码,这些代码将查看文本文件并将行拆分为 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

这就是文本文件 提前致谢

它会在换行符 '\n' 之前打印出一个空字符 '' - 我想你想要的是这样的:

lines = f.read().splitlines()
#This will only get the value for one line
scores[0], scores[1] = lines[0].split(':')

#Or to get both lines:
i=0
for line in f.read().splitlines():
    scores[i][0], scores[i][1] = line.split(':')
    i += 1

这里 line=(f.readline(x)) 是这样的 (["content of file"]) 即它是元组内列表中的文件内容。

您需要将 x 中定义的大小从 0 更改为某个值,否则不要使用它。即从 line = (f.readline(x))line = f.readline() 现在它将是一个字符串。

现在您可以对字符串对象使用拆分操作。将 a, b = (line).split(':') 更改为 a, b = line.split(':')

所以新代码将是

# opening/cretaing a file and adding data
with open("scores.txt", 'a') as f:   
    f.write("\n")    
    f.write("andrew:78")    
    f.write("\n")    
    f.write("karen:64")    


# creating a dictionary to save data of name and score respectively

scores = {'name':[], 'score':[]}

# again opening the file in read mode
with open("scores.txt", 'r') as f:
    data = f.readlines() # reading all line in file at single time
    for each_line in data: 
        if line.split(':'): # checking if each line has format <name>:<score> or not, if yes then add that data to scores dict
            name, score = line.split(':')
            scores['name'].append(name)
            scores['score'].append(score)

# seeing the result
print(scores)

这段代码是否实现了你想要的?

with open("scores.txt", "a") as f:
    f.write(
        "\nandrew:78"
        "\nkaren:64"
    )

scores = []

with open("scores.txt", "r") as f:
    lines = f.readlines()
    for line in lines:
        if ":" in line:
            a, b = (line).split(":")

            scores.append({a: b})

您可能遇到了一个错误,因为某些行(空白行)没有“:”,所以该行只是您尝试将其解压缩为 2 个变量的一个字符串。