patternpythonCritical
Print string to text file
Viewed 0 times
filestringtextprint
Problem
In the following code, I want to substitute the value of a string variable
How to do this?
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?
Solution
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
For python2.7 and higher you can use
In Python3, there is an optional
Python3.6 introduced f-strings for another alternative
with open("Output.txt", "w") as text_file:
text_file.write("Purchase Amount: %s" % TotalAmount)This is the explicit version (but always remember, the context manager version from above should be preferred):
text_file = open("Output.txt", "w")
text_file.write("Purchase Amount: %s" % TotalAmount)
text_file.close()If you're using Python2.6 or higher, it's preferred to use
str.format()with open("Output.txt", "w") as text_file:
text_file.write("Purchase Amount: {0}".format(TotalAmount))For python2.7 and higher you can use
{} instead of {0}In Python3, there is an optional
file parameter to the print functionwith open("Output.txt", "w") as text_file:
print("Purchase Amount: {}".format(TotalAmount), file=text_file)Python3.6 introduced f-strings for another alternative
with open("Output.txt", "w") as text_file:
print(f"Purchase Amount: {TotalAmount}", file=text_file)Code Snippets
with open("Output.txt", "w") as text_file:
text_file.write("Purchase Amount: %s" % TotalAmount)text_file = open("Output.txt", "w")
text_file.write("Purchase Amount: %s" % TotalAmount)
text_file.close()with open("Output.txt", "w") as text_file:
text_file.write("Purchase Amount: {0}".format(TotalAmount))with open("Output.txt", "w") as text_file:
print("Purchase Amount: {}".format(TotalAmount), file=text_file)with open("Output.txt", "w") as text_file:
print(f"Purchase Amount: {TotalAmount}", file=text_file)Context
Stack Overflow Q#5214578, score: 1688
Revisions (0)
No revisions yet.