888

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?

Georgy
  • 12,464
  • 7
  • 65
  • 73
The Woo
  • 17,809
  • 26
  • 57
  • 71

8 Answers8

1592

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)
mit
  • 11,083
  • 11
  • 50
  • 74
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
  • 2
    Assuming TotalAmount is an integer, shouldn't the "%s" be a "%d"? – Rui Curado Aug 22 '13 at 10:46
  • 6
    @RuiCurado, if `TotalAmount` is an `int`, either `%d` or `%s` will do the same thing. – John La Rooy Aug 22 '13 at 10:54
  • 2
    Great answer. I'm seeing a syntax error with a nearly identical use case: `with . . .: print('{0}'.format(some_var), file=text_file)` is throwing: `SyntaxError: invalid syntax` at the equal sign... – nicorellius Apr 06 '16 at 19:51
  • 4
    @nicorellius, if you wish to use that with Python2.x you need to put `from __future__ import print_function` at the top of the file. Note that this will transform _all_ of the print statements in the file to the newer function calls. – John La Rooy Apr 06 '16 at 20:48
  • To make sure know what the variable type is often convert it to make sure, ex: "text_file.write('Purchase Amount: %s' % str(TotalAmount))" which will work with lists, strings, floats, ints, and anything else that is convertable to a string. – EBo Sep 09 '16 at 11:19
  • @EBo, format strings work slightly differently in different languages. In Python, `%s` means call `obj.__str__`. So it's identical behaviour to calling `str` explicitly. – John La Rooy Sep 11 '16 at 06:58
  • agreed, but on the fly it is sometimes hard to know what to change when a diagnostic statement hickups. Also while I try to be consistent withthe variable type there is no guarantees. – EBo Sep 12 '16 at 19:36
  • @EBo, But it is guaranteed. If `%s` can't convert to a `str`, then `str()` can't either. If this isn't clear yet, perhaps you can open a new question about it. – John La Rooy Sep 13 '16 at 01:14
  • I will have to track down an example where this worked for me. I may have misunderstood the issue and a solution that worked. What you say makes sense. – EBo Oct 24 '16 at 11:02
  • why did you not do `w+`? – Charlie Parker Oct 18 '20 at 20:16
63

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

Community
  • 1
  • 1
user1767754
  • 23,311
  • 18
  • 141
  • 164
48

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()
Rajiv Sharma
  • 6,746
  • 1
  • 52
  • 54
  • why did you not do `w+`? – Charlie Parker Oct 18 '20 at 20:16
  • 5
    `print(your_data, file=open(...))` will leave the file opened – Mikhail Feb 17 '21 at 16:17
  • The best answer for python 3 because you can utilize features of print function. You don't need to map to str and concatenate elements, just give each element to print as parameters and let print function do the rest. Ex: print(arg, getattr(args, arg), sep=", ", file=output) – ibilgen Dec 29 '21 at 11:31
32

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}")
naoki fujita
  • 689
  • 1
  • 9
  • 13
23

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')
Guy s
  • 1,586
  • 3
  • 20
  • 27
2

I guess lots of people use the answers here as a general quick reference to how to write a string to a file. Quite often when I write a string to a file, I'd want to specify the file encoding and here is how to do it:

with open('Output.txt', 'w', encoding='utf-8') as f:
    f.write(f'Purchase Amount: {TotalAmount}')

If you don't specify the encoding, the encoding used is platform-dependent (see the docs). I think the default behavior is rarely useful from a practical point of view and could lead to nasty problems. That's why I almost always set the encoding parameter.

at54321
  • 8,726
  • 26
  • 46
1

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')
Akhilesh_IN
  • 1,217
  • 1
  • 13
  • 19
0

If you need to split a long HTML string in smaller strings and add them to a .txt file separated by a new line \n use the python3 script below. In my case I am sending a very long HTML string from server to client and I need to send small strings one after another. Also be careful with UnicodeError if you have special characters like for example the horizontal bar or emojis, you will need to replace them with others chars beforehand. Also make sure you replace the "" inside your html with ''

#decide the character number for every division    
divideEvery = 100

myHtmlString = "<!DOCTYPE html><html lang='en'><title>W3.CSS Template</title><meta charset='UTF-8'><meta name='viewport' content='width=device-width, initial-scale=1'><link rel='stylesheet' href='https://www.w3schools.com/w3css/4/w3.css'><link rel='stylesheet' href='https://fonts.googleapis.com/css?family=Lato'><link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css'><style>body {font-family: 'Lato', sans-serif}.mySlides {display: none}</style><body></body></html>"

myLength = len(myHtmlString)
division = myLength/divideEvery
print("number of divisions")
print(division)

carry = myLength%divideEvery
print("characters in the last piece of string")
print(carry)

f = open("result.txt","w+")
f.write("Below the string splitted \r\n")
f.close()

x=myHtmlString
n=divideEvery
myArray=[]
for i in range(0,len(x),n):
    myArray.append(x[i:i+n])
#print(myArray)

for item in myArray:
    f = open('result.txt', 'a')
    f.write('server.sendContent(\"'+item+'\");' '\n'+ '\n')

f.close()
Pietro
  • 127
  • 6