Search code examples
pythonioreadline

Importing output from two seperate lines from textfile and turning them into variables in Python


I have a python script that outputs EX. "Gender: Male" and "Age: 25-32" on seperate lines in a textfile. This same script can print out different ages and male and female gender based on the facial recognition application. I need to RETRIEVE these seperate lines and convert them into variables. This is what I have so far.

    infile = open('output.txt', 'r')

    g_line = infile.readline()
    a_line = infile.readline()

    with open('output.txt', 'r') as myfile:
        g_line = myfile.readline()
        a_line = myfile.readline()
    print(g_line)
    print(a_line)

Solution

  • If your file looks like:

    Gender: Male
    Age: 25-32
    

    Try:

    with open("output.txt", "r") as f:
        gender = f.readline().split(":")[-1].strip()
        age = f.readline().split(":")[-1].strip()
        print(gender) # Male
        print(age) # 25-32