pythonstringlistwritetofile

Writing list to file for reuse at a later date


I have a python file that requires a username and password for authentication. These username and passsword details are saved to the file in the format

    userlist = [[username, password], [username1, password1]]

and so on. This works but when I write my list to a file, I will write it as a string like this:

    name_write_file = open("names.txt", "w")
    name_write_file.writelines(str(name_list))
    print("user data successfully saved to file")
    name_write_file.close()

Later on in the code, I need to recognise a username in order to initiate the login sequence and I do this using

    userlist[0] 

Normally this should return "username" but instead it now returns "[" (the first parenthesis from the string saved to file)

Any way to fix this?

Thanks in advance


Solution

  • A quick way to save and retrieve a list is to use eval:

    name_list = [['username', 'password'], ['username1', 'password1']]
    
    name_write_file = open("names.txt", "w")
    name_write_file.writelines(str(name_list))
    print("user data successfully saved to file")
    name_write_file.close()
    
    with open("names.txt") as f:
       name_list2 = eval(f.read())
    
    print(name_list)
    print(name_list2)
    print(name_list2[0])
    

    Output

    [['username', 'password'], ['username1', 'password1']]
    [['username', 'password'], ['username1', 'password1']]
    ['username', 'password']