I have a text file named login.txt
has the following data:
{'Username':'hazem', 'Password':'000'}
{'Username':'john', 'Password':'123'}
And I have a function has two parameters Username
and Password
Once I pass the parameters as example john
and 123
I want to check if the username and password is right or not from the text file.
But I don't know exactly how to read the key value pairs data from a text file.
Thanks in advance.
CodePudding user response:
Use a combination of iterating over the files ast.literal_eval.
For example:
import ast
file_location = 'SomeFileLocation\text_file.txt'
# Open File and iterate over lines
with open(file_location, 'r ') as f:
for single_line in f:
dict_to_check = ast.literal_eval(single_line)
user_name = dict_to_check['Username']
password = dict_to_check['Password']
CodePudding user response:
Save the credentials to JSON file and you can access them with JSON libary
login.json
[
{
"username": "john",
"password": "1234"
},
{
"username": "johny",
"password": "12sdfds34"
}
]
import json
with open('login.json') as json_data:
d = json.load(json_data)
for i in d:
print(i["username"], i["password"])