简体   繁体   中英

How do I parse a file and substitute the environment variables with values in Python

I have a text file (lets call it file1.txt), it contains the following lines: "read model $path_1"

How do I replace the value of path_1 variable in this text file and write it to another file (lets call it file2.txt) with same contents but $path_1 variable expanded. My file2.txt should contain something like the following: "read model /home/Aero/test"

Is there any parser in python available to do this job? I looked into ConfigParser module but looks to me that it needs a config file with variable=value pair.

Regards, Sandhya

string.Template

>>> from string import Template
>>> s = Template('$who likes $what')
>>> s.substitute(who='tim', what='kung pao')
'tim likes kung pao'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM