In the following code, I want to substitute the value of a string variable TotalAmount into the text document, with Python:
text_file = open("Output.txt", "w")
text_file.write("Purchase Amount: " 'TotalAmount')
text_file.close()
How to do this?
It is strongly advised to use a context manager. As an advantage, it is made sure the file is always closed, no matter what:
This is the explicit version (but always remember, the context manager version from above should be preferred):
If you’re using Python2.6 or higher, it’s preferred to use
str.format()For python2.7 and higher you can use
{}instead of{0}In Python3, there is an optional
fileparameter to theprintfunctionPython3.6 introduced f-strings for another alternative