Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read file into a list and replace the variables with values in Python

Tags:

python

I have a data.txt file with the following lines:

this is sample {data1}
this one is {data2}
again {data1}

And I have this code to read the file's lines into a list and print the list:

    data1 = 'line 1'
    data2 = 'line 2'

    with open('data.txt') as file:
        lines = file.read().splitlines()

    print(lines)

The output is:

['this is sample {data1}', 'this one is {data2}', 'again {data1}']

Now, How can I replace the variables with their value and have it like:

['this is sample line 1', 'this one is line 2', 'again line 1']
like image 771
Kourosh Nomanpour Avatar asked Mar 26 '26 23:03

Kourosh Nomanpour


1 Answers

Put the replacements in a dictionary, then call format().

values = {'data1': 'line 1', 'data2': 'line 2'}
print([line.format(**values) for line in lines])
like image 65
Barmar Avatar answered Mar 28 '26 14:03

Barmar