read values from text file in python

Issue

I want to include texts from a .text file in python and use them as values

in text file

LICENSE CODE = XXXX-XXXX-XXXX-XXXX

ACTIVATION CODE = XXXX-XXXXXXXXXXXXXXXX

and in python, I want to read the file with the open() command and identify license code and activation code and use the values in the code

Solution

A regex version:

import re


def find_regex_1(k, s):
    reg = f'{k}\s*=\s*(\S+)'
    return re.search(reg, s).group(1)


def read_configs(config_file):
    with open(config_file, "r") as f:
        content = f.read()
        license_code = find_regex_1('LICENSE CODE', content)
        activation_code = find_regex_1('ACTIVATION CODE ', content)
    return license_code, activation_code


if __name__ == '__main__':
    license_code, activation_code = read_configs('config.txt')
    print(license_code, activation_code)

Answered By – Lei Yang

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published