1

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

2 Answers 2

4

os.path.expandvars()

Sign up to request clarification or add additional context in comments.

2 Comments

This works. Thank you. But is there a way to make it work for even shell variables, say I set some variable $path_1=/home/Aero/test in the shell, but using os.path.expandvars("path_1") doesn't work.
Maybe because you are setting shell (bash) variables, and not environment variables, @Sandhya. Try using EXPORT or SET nixcraft.com/shell-scripting/…
3

string.Template

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.