I'm using Python to open a text document:
text_file = open("Output.txt", "w")
text_file.write("Purchase Amount: " 'TotalAmount')
text_file.close()
I want to enter the string called "TotalAmount" into the text document. Can someone please let me know how to do this?
If you are using numpy, printing a single (or multiply) strings to a file can be done with just one line:
Easier way to do in Linux and Python,
(OR)
If you use a context manager, the file is closed automatically for you
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
file
parameter to theprint
functionPython3.6 introduced f-strings for another alternative
I think the easier way to do that is via appending the text you want to set to the file using
here is an example for that
"a" refer to append mood , it will append the text you want to write to the end of the text in the your file
In case you want to pass multiple arguments you can use a tuple
More: Print multiple arguments in python
With using pathlib module, indentation isn't needed.
As of python 3.6, f-strings is available.