1

Using the answer on Stack Overflow shown on this link: https://stackoverflow.com/a/4804039, I have attempted to read in the file contents into a dictionary. There is an error that I cannot seem to fix.

Code

def login():
                     print("====Login====")

                     userinfo={}
                     with open("userinfo.txt","r") as f:
                               for line in f:
                                        (key,val)=line.split()
                                        userinfo[key]=val
                     print(userinfo)

File Contents

{'user1': 'pass'}
{'user2': 'foo'}
{'user3': 'boo'}

Error:

 (key,val)=line.split()
ValueError: not enough values to unpack (expected 2, got 0)

I have a question to which I would very much appreciate a two fold answer

  1. What is the best and most efficient way to read in file contents, as shown, into a dictionary, noting that it has already been stored in dictionary format.

  2. Is there a way to WRITE to a dictionary to make this "reading" easier? My code for writing to the userinfo.txt file in the first place is shown below

Write code

 with open("userinfo.txt","a",newline="")as fo:
                               writer=csv.writer(fo)
                               writer.writerow([{username:password}])

Could any answers please attempt the following

  1. Provide a solution to the error using the original code

  2. Suggest the best method to do the same thing (simplest for teaching purposes) Note, that I do not wish to use pickle, json or anything other than very basic file handling (so only reading from a text file or csv reader/writer tools). For instance, would it be best to read the file contents into a list and then convert the list into a dictionary? Or is there any other way?

  3. Is there a method of writing a dictionary to a text file using csv reader or other basic txt file handling, so that the reading of the file contents into a dictionary could be done more effectively on the other end.

Update:

Blank line removed, and the code works but produces the erroneous output:

{"{"Vjr':": "'open123'}", "{'mvj':": "'mvv123'}"}

I think I need to understand the split and strip commands and how to use them in this context to produce the desired result (reading the contents into a dictionary userinfo)

Compoot
  • 2,227
  • 6
  • 31
  • 63

2 Answers2

1

Well let's start with the basics first. The error message:

ValueError: not enough values to unpack (expected 2, got 0)

means a line was empty, so do you have a blank line in the file?

ptcmark
  • 79
  • 4
  • Thank you -yes. Blank line removed. and now the following: {"{'benjr':": "'open123'}", "{'marvj':": "'marv123'}"} Will update the question to include this. Am still after the best way to write/read in file contents to a dictionary. My initial thoughts were to write as a list, and read in as a dictionary using the code shown on the link I gave. I feel sure there is an easier way though ...Thank you again – Compoot Sep 05 '17 at 18:54
0

Yes, there are other options on saving your dictionary out and bringing it back, but first you should understand this, and may work just fine for you. :-) The split() is acting on the string you read from the file, and by default will split on the space, so that is what you are seeing. You could format your text file like 'username:pass' instead and then use split(':").

File Contents

user1:pass
user2:foo
user3:boo

Code

def login():
    print("====Login====")

    userinfo={}
    with open("userinfo.txt","r") as f:
        for line in f:
            (key,val)=line.split(':')
            userinfo[key]=val.strip()
        print(userinfo)

if __name__ == '__main__':
    login()

This simple format may be best if you want to be able to edit the text file by hand, and I like to keep it simple as possible. ;-)

ptcmark
  • 79
  • 4