757
votes

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?

6
why did you not do w+?Charlie Parker

6 Answers

1388
votes

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)
53
votes

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

41
votes

If you are using Python3.

then you can use Print Function :

your_data = {"Purchase Amount": 'TotalAmount'}
print(your_data,  file=open('D:\log.txt', 'w'))

For python2

this is the example of Python Print String To Text File

def my_func():
    """
    this function return some value
    :return:
    """
    return 25.256


def write_file(data):
    """
    this function write data to file
    :param data:
    :return:
    """
    file_name = r'D:\log.txt'
    with open(file_name, 'w') as x_file:
        x_file.write('{} TotalAmount'.format(data))


def run():
    data = my_func()
    write_file(data)


run()
23
votes

If you are using numpy, printing a single (or multiply) strings to a file can be done with just one line:

numpy.savetxt('Output.txt', ["Purchase Amount: %s" % TotalAmount], fmt='%s')
19
votes

With using pathlib module, indentation isn't needed.

import pathlib
pathlib.Path("output.txt").write_text("Purchase Amount: {}" .format(TotalAmount))

As of python 3.6, f-strings is available.

pathlib.Path("output.txt").write_text(f"Purchase Amount: {TotalAmount}")
1
votes

use of f-string is a good option because we can put multiple parameters with syntax like str,

for example:

import datetime

now = datetime.datetime.now()
price = 1200
currency = "INR"

with open("D:\\log.txt","a") as f:
    f.write(f'Product sold at {currency} {price } on {str(now)}\n')