从文本文件的两行中导入输出并将它们转换为 Python 中的变量

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

我有一个 python 脚本可以输出 EX。 "Gender: Male" 和 "Age: 25-32" 在文本文件中的不同行上。同样的脚本可以根据面部识别应用程序打印出不同的年龄和男女性别。我需要检索这些单独的行并将它们转换为变量。这是我目前所拥有的。

    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)

如果您的文件如下所示:

Gender: Male
Age: 25-32

尝试:

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