简体   繁体   中英

How to fix ValueError: not enough values to unpack (expected 2, got 1)

I am working with a text file where I'm making a dict and zip function for a login page. But for some reasons, it gives me the ValueError from time to time. This usually happens when I manually edit or remove data from the text file and will be fixed if I create another text file but I can't keep doing that. So please help me.

The Text File

shanm, @Yolz3345
Jiaern, @Valorant
Steve, ImaG@nius

The code

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

The Error I get from time to time

    a,b = info.split(", ")
ValueError: not enough values to unpack (expected 2, got 1)

As mentioned in the comment, this indicates a line without a comma. Most likely a return character at the end of the last line, meaning you have one empty line at the end.

Most likely it is the last line in the file which is empty, ie \\n .

How can you debug it? add a try-catch and print info

How can you fix it? either delete the last line in the file or try-catch and ignore.

You can use the .readlines() function to get list containing all lines except the last line if its empty.

New Code:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM