How to Write String to Text File in Python?

Python – Write String to Text File

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.
Python - Write String to Text File

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

Output

29

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.

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

Output

29

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.

Summary

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