Print string to text file

PythonStringTextFile Io

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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)

Solution 2 - Python

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: https://stackoverflow.com/questions/15286401/print-multiple-arguments-in-python

Solution 3 - Python

> 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()

Solution 4 - Python

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}")

Solution 5 - Python

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')

Solution 6 - Python

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')

Solution 7 - Python

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()

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionThe WooView Question on Stackoverflow
Solution 1 - PythonJohn La RooyView Answer on Stackoverflow
Solution 2 - Pythonuser1767754View Answer on Stackoverflow
Solution 3 - PythonRajiv SharmaView Answer on Stackoverflow
Solution 4 - Pythonnaoki fujitaView Answer on Stackoverflow
Solution 5 - PythonGuy sView Answer on Stackoverflow
Solution 6 - PythonAkhilesh_INView Answer on Stackoverflow
Solution 7 - PythonPietroView Answer on Stackoverflow