3 回答

TA貢獻(xiàn)1816條經(jīng)驗(yàn) 獲得超6個(gè)贊
這 line=(f.readline(x))是類似的東西 (["content of file"]),即它是元組內(nèi)列表中的文件內(nèi)容。
您需要將其定義的大小x從 0 更改為某個(gè)值,或者不使用它。即 fromline = (f.readline(x))到line = f.readline()現(xiàn)在將是一個(gè)字符串。
現(xiàn)在您可以對(duì)字符串對(duì)象使用拆分操作。改成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)

TA貢獻(xiàn)1806條經(jīng)驗(yàn) 獲得超8個(gè)贊
這段代碼能達(dá)到你想要的效果嗎?
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})
您可能遇到錯(cuò)誤,因?yàn)槟承┬校瞻仔校](méi)有“:”,因此該行只是一個(gè)字符串,您試圖將其解壓縮為兩個(gè)變量。

TA貢獻(xiàn)1836條經(jīng)驗(yàn) 獲得超4個(gè)贊
它會(huì)在換行符 '\n' 之前打印出一個(gè)空字符 '' - 我認(rè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
添加回答
舉報(bào)