W3.CSS Template

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?

8 Answers 8

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: ".format(TotalAmount)) 

For python2.7 and higher you can use <> instead of

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: ", file=text_file) 

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, 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.

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.

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)) 
your_data = print(your_data, file=open('D:\log.txt', 'w')) 

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

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)

Читайте также:  Callback php on line

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

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

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

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.

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  on \n') 

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 = "body .mySlides " 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() 

Источник

Write String to Text File in Python

In this Python tutorial, you will learn how to write a string value to a text file, using write() method of file class.

Python – Write String to Text File

To write string to a file in Python, we can call write() function on the text file object and pass the string as argument to this write() function.

In this tutorial, we will learn how to write Python String to a file, with the help of some Python example programs.

Following is the step by step process to write a string to a text file.

  1. Open the text file in write mode using open() function. The function returns a file object.
  2. Call write() function on the file object, and pass the string to write() function as argument.
  3. Once all the writing is done, close the file using close() function.

Examples

1. Write string to new text file

The following is an example Python program in its simplest form to write string to a text file.

Читайте также:  Centos установка php разных версий

Python Program

#open text file text_file = open("D:/data.txt", "w") #write string to file text_file.write('Python Tutorial by TutorialKart.') #close file text_file.close()

Reference tutorials for the above program

When we run this program, a new file is created named data.txt in D: drive and the string is written to the file. But to programmatically confirm, you can use the value returned by write() function. write() function returns the number of bytes written to the file.

Python Program

#open text file text_file = open("D:/data.txt", "w") #write string to file n = text_file.write('Python Tutorial by TutorialKart.') #close file text_file.close() print(n)

2. Write string value to an existing file

If you try to write a string to an existing file, be careful. When you create a file in write mode and call write() function, existing data is lost and new data is written to the file.

For instance, in the previous example, we created a file and written some data to it.

Now we shall run the following example.

Python Program

#open text file text_file = open("D:/data.txt", "w") #write string to file n = text_file.write('Hello World!') #close file text_file.close()

The existing file is overwritten by the new content.

Note: If you would like to append data to a file, open file in append mode and then call write() function on the file object.

Conclusion

In this Python Tutorial, we learned how to write a string to a text file.

Источник

How to Write String to Text File in Python?

Now you can save or write string to text a file in persistent data storage using Python.

To write string to a Text File, follow these sequence of steps:

  1. Open file in write mode using open() function.
  2. Write string to the file using write() method.
  3. Close the file using close() method.

Examples

1. Write string to text file

In the following example, we will take a string constant and write the string to a text file by following the above said sequence of steps.

Python Program

text_file = open("sample.txt", "w") n = text_file.write('Welcome to pythonexamples.org') text_file.close()

The write() method returns the number of characters written to the text file.

Note that this kind of writing to text file, overwrites the data, if the file is already present. If the file is not present, it creates a new file and then writes the string to the file.

2. Write string to text file in text mode

A file can be opened in two modes: the first one is text mode and the second one is binary mode. By default a file is opened in text mode. However, you can explicitly specify the mode.

In the following example, we will open the file in text mode by appending “t” to the mode and write the string to a text file by following the sequence of steps mentioned at the start of this tutorial.

Python Program

text_file = open("sample.txt", "wt") n = text_file.write('Welcome to pythonexamples.org') text_file.close()

Writing other than String to Text File

If you would like to write any Python object other than string or a bytes object to a file, using write() method, you should first convert that Python object to a string or bytes object.

Читайте также:  Org hibernate cfg configuration java

Summary

In this tutorial of Python Examples, we learned how to write a string to a text file, with the help of example programs.

Источник

How to Write a String to a Text File using Python

Data to Fish

Steps to Write a String to a Text File using Python

Step 1: Specify the path for the text file

To begin, specify the path where the text file will be created.

For example, let’s suppose that a text file will be created under the following path:

Step 2: Write a string to a text file using Python

Next, write your string to the text file using this template:

text_file = open(r'path where the text file will be created\file name.txt', 'w') my_string = 'type your string here' text_file.write(my_string) text_file.close()
  • The path where the text file will be created is: C:\Users\Ron\Desktop\Test
  • The file name (with the txt file extension) is: Example.txt
  • my_string contains the following text: ‘This is a Test

So the full Python code would look as follows (don’t forget to place ‘r‘ before your path name to avoid any errors in the path):

text_file = open(r'C:\Users\Ron\Desktop\Test\Example.txt', 'w') my_string = 'This is a Test' text_file.write(my_string) text_file.close()

Once you run the code (adjusted to your path), you’ll then see the new text file in your specified location.

If you open the text file, you’ll see the actual string:

Overwrite the String

What if you want to overwrite the original string with a new value?

For instance, what if you want to change the string to the following value:

This is a NEW Test

In that case, simply edit the text as follows:

my_string = 'This is a NEW Test'

So the new Python code would look like this:

text_file = open(r'C:\Users\Ron\Desktop\Test\Example.txt', 'w') my_string = 'This is a NEW Test' text_file.write(my_string) text_file.close()

Run the code, and you’ll see the new string:

List of Strings

Say that you want to display a list of strings in your text file.

Here is an example of a list with strings:

my_list = ['This is a Test', 'This is ALSO a Test', 'This is a FINAL Test']

In that case, you may use a for loop to display your list of strings in the text file:

text_file = open(r'C:\Users\Ron\Desktop\Test\Example.txt', 'w') my_list = ['This is a Test', 'This is ALSO a Test', 'This is a FINAL Test'] for i in my_list: text_file.write(i + '\n') text_file.close()

You’ll now see that each of the strings is presented in a new line:

Dealing with Integers

If you try to print integers into the text file, you’ll get the following error:

write() argument must be str, not int

You may then choose to convert the integers to strings.

For example, let’s suppose that you have two integers (3 and 5), and you want to present the sum of those integers in the text file.

In that case, you may apply the following syntax to achieve the above goal (notice that str() was used to convert the integers to strings):

text_file = open(r'C:\Users\Ron\Desktop\Test\Example.txt', 'w') sum_values = 3 + 5 text_file.write(str(sum_values)) text_file.close()

You’ll then get the sum of 8 in the text file:

Источник

Оцените статью