Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print string to text file

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 substitute the value of a string variable TotalAmount into the text document. Can someone please let me know how to do this?

like image 216
The Woo Avatar asked Mar 07 '11 00:03

The Woo


People also ask

How do you print a text file in Python?

First, open the text file for writing (or append) using the open() function. Second, write to the text file using the write() or writelines() method. Third, close the file using the close() method.

How do I print a .TXT file?

Once you've got Notepad's settings right, try this trick: Open Windows Explorer and right-click a text file. On the context menu that appears, click Print. You no longer need to open Notepad first to tell it your preferences. Notepad remembers them for you.


2 Answers

It is strongly advised to use a context manager. As an advantage, it is made sure the file is always closed, no matter what:

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 function

with 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) 
like image 108
John La Rooy Avatar answered Sep 29 '22 08:09

John La Rooy


In case you want to pass multiple arguments you can use a tuple

price = 33.3 with open("Output.txt", "w") as text_file:     text_file.write("Purchase Amount: %s price %f" % (TotalAmount, price)) 

More: Print multiple arguments in python

like image 21
user1767754 Avatar answered Sep 29 '22 08:09

user1767754