How to get a specific field from a text file using python

Question:

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.

Asked By: Hazem Behairy

||

Answers:

Use a combination of iterating over the files + ast.literal_eval.

For example:

import ast

file_location = 'SomeFileLocationtext_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']
    
Answered By: zurcam

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"])
Answered By: valtteri k
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.