A M
A M

Reputation: 35

Why am I getting value error in viewing a file?

I am trying to create a password manager in Python and I am getting an Value Error. Below is my code that I've written for the password manager. It uses inputs for password.



def view():
    with open("passwords.txt", "r") as f:
        for line in f.readline():
            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":
        quit()
    if mode == "view":
        view()
    elif mode == "add":
        add()
    else:
        print("You have entered an invalid mode")
        continue

Here is the error I'm getting when running and entering inputs:

  File "C:\Users\user\Documents\Python\exercises\passwordmanag.py", line 22, in <module>
    view()
  File "C:\Users\user\Documents\Python\exercises\passwordmanag.py", line 8, in view
    user, passw = data.split("|")
ValueError: not enough values to unpack (expected 2, got 1)

Can someone please help me out and guide me on how to fix this error?

Thank you.

Upvotes: 1

Views: 258

Answers (1)

Sameer Ali
Sameer Ali

Reputation: 137

def view():
    with open("passwords.txt", "r") as f:
        for line in f:
            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":
        quit()
    if mode == "view":
        view()
    elif mode == "add":
        add()
    else:
        print("You have entered an invalid mode")
        continue

Context: You were trying to read each character of the line rather than reading each line therefore it was giving you an error when trying to split.

Upvotes: 2

Related Questions