我正在處理一個文本檔案,我正在為登錄頁面制作 dict 和 zip 函式。但由于某些原因,它不時給我 ValueError。這通常發生在我手動編輯或從文本檔案中洗掉資料時,如果我創建另一個文本檔案但我不能繼續這樣做,則會得到修復。所以請幫助我。
文本檔案
shanm, @Yolz3345
Jiaern, @Valorant
Steve, ImaG@nius
編碼
#FOR LOGIN DETAILS
list_un = []
list_ps = []
members_list = open("det.txt", "r")
for info in members_list:
a,b = info.split(", ")
b = b.strip()
list_un.append(a)
list_ps.append(b)
data = dict(zip(list_un, list_ps))
我不時得到的錯誤
a,b = info.split(", ")
ValueError: not enough values to unpack (expected 2, got 1)
uj5u.com熱心網友回復:
正如評論中提到的,這表示一行沒有逗號。最有可能是最后一行末尾的回傳字符,這意味著末尾有一個空行。
uj5u.com熱心網友回復:
最有可能的是檔案中的最后一行是空的,即\n.
你怎么能除錯它?添加 try-catch 并列印info
你怎么能修好呢?要么洗掉檔案中的最后一行,要么嘗試捕獲并忽略。
uj5u.com熱心網友回復:
如果最后一行為空,您可以使用 .readlines() 函式獲取包含除最后一行之外的所有行的串列。
新代碼:
list_un = []
list_ps = []
members_list = open("det.txt", "r")
for info in members_list.readlines():
a,b = info.split(", ")
b = b.strip()
list_un.append(a)
list_ps.append(b)
data = dict(zip(list_un, list_ps))
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/321780.html
