Home > Back-end >  How to fix ValueError: not enough values to unpack (expected 2, got 1)
How to fix ValueError: not enough values to unpack (expected 2, got 1)

Time:10-17

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)

CodePudding user response:

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.

CodePudding user response:

Most likely it is the last line in the file which is empty, i.e. \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.

CodePudding user response:

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