亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

嘗試將文本文件放入數組時,python 值錯誤預期 2 收到一個

嘗試將文本文件放入數組時,python 值錯誤預期 2 收到一個

慕尼黑的夜晚無繁華 2024-01-15 21:15:47
我試圖獲取一些代碼,該代碼將查看一個文本文件并將行拆分為 2 個變量,但是當我運行此代碼時,我收到錯誤 ValueError: 沒有足夠的值來解包(預期 2,得到 1), 代碼是:x=0f = 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這是文本文件,提前致謝
查看完整描述

3 回答

?
瀟湘沐

TA貢獻1816條經驗 獲得超6個贊

這 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 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)


查看完整回答
反對 回復 2024-01-15
?
慕森卡

TA貢獻1806條經驗 獲得超8個贊

這段代碼能達到你想要的效果嗎?


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})

您可能遇到錯誤,因為某些行(空白行)沒有“:”,因此該行只是一個字符串,您試圖將其解壓縮為兩個變量。


查看完整回答
反對 回復 2024-01-15
?
HUH函數

TA貢獻1836條經驗 獲得超4個贊

它會在換行符 '\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


查看完整回答
反對 回復 2024-01-15
  • 3 回答
  • 0 關注
  • 182 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號