Home > Software engineering >  ValueError: too many values to unpack (expected 2) on a simple Python function
ValueError: too many values to unpack (expected 2) on a simple Python function

Time:11-17

I'm coding this password manager program and keep getting this error message when I use the view function:

    File "c:\Users\user\Desktop\password_manager.py", line 7, in view
    user, passw = data.split("|")
ValueError: too many values to unpack (expected 2)

This is the program so far:

master_pwd = input("What is the master password?")

def view():
    with open("passwords.txt", "r") as f:
        for line in f.readlines():
            data = line.rstrip()
            user, passw = data.split("|")
            print("User:", user, "Password:", passw)

        

def add():
    name = input("Account name: ")
    pwd = input("Password: ")

    with open("passwords.txt", "a") as f:
        f.write(name   "|"   pwd   "\n")
    

while True:
    mode = input("Would you like to add a new password or view existing ones (view, add)? Press q to quit. ").lower()
    if mode == "q":
        break
    if mode == "view":
        view()
    elif mode == "add":
        add()
    else:
        print("Invalid mode.")
        continue

I tried using the .split() method to one variable at a time but it also resulted in the error. I thought the problem could be caused by the comma in user, passw = data.split("|") being deprecated, but I failed to find an alternative.

CodePudding user response:

The .split() function is returning more than 2 values in a list and therefore cannot be unpacked into only 2 variables. Maybe you have a password or username with a | in it which would cause that.

I suggest to simply print(data.split('|')) for a visual of what is happening. It will probably print out a list with more than two values.

CodePudding user response:

Check your password file to be sure there aren't "|" characters in a username or password that are creating additional splits.

If your data is good, you could catch the remaining elements in a list:

user, passw, *other = data.split("|")
  • Related