Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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']
    
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading