In this article, you will see how you can write content to text files and read content from a text file using the Python programming language. Python comes with built-in functionalities for opening text files and reading and writing contents from the file. So let’s begin without ado.

Table of Contents

  1. Opening a Text File
  2. Writing text to Files
  3. Writing Single Line of Text
  4. Writing Multiple Lines of Text
  5. Appending Text at the End of a File
  6. Reading Text from Files
  7. Reading Single line of Text
  8. Reading Multiple Lines of Text
  9. Reading all the Text

Reading and Writing Text Files with Python

Opening a Text File

To open a text file in a Python application, you can use the open() method. The path to the text file is passed as the first parameter and the file permission is passed as a second parameter to the text file. Let’s open a very simple file using Python:

file_handler = open("E:/my_file.txt", "w+")

If you run the above script, the file “my_file.txt” will be opened in your application. The second parameter “w+” specifies that the file should be opened for both reading and writing text. It is important to mention that the file permission “w+” will create the file that you want to open, in case the file doesn’t exit at the specified path. The following table contains details of all the various file permissions that you can use to open a  file in Python.

Permission Description
r Opens file for read-only
r+ Opens file for reading and writing
rb Only Read file in binary
rb+ Opens file to read and write in binary
w Opens file to write only. Overwrites existing files with the same name. The file is created if it doesn’t exist already.
wb Opens file to write only in binary. Overwrites existing files with the same name. The file is created if it doesn’t exist already.
w+ Opens file for reading and writing. The file is created if it doesn’t exist already.
wb+ Opens file to read and write in binary. Overwrites existing files with the same name. The file is created if it doesn’t exist already.
a Opens a file for appending content at the end of the file
a+ Opens file for appending as well as reading content
ab Opens a file for appending content in binary
ab+ Opens a file for reading and appending content in binary

Writing Text to Files

Now you know how to open a text file in Python, let’s see how you can write some text to a file.

Writing Single Line of Text

To write a single line of text, you can simply use the write() method from the object returned by the open() function.  Look at the following example:

file_handler = open("E:/my_file.txt", "w+")
file_handler.write("this is the first line of the file")
file_handler.close()

In the above script, you perform three steps. First, you open a file using the open() method and “w+” permission. Next, you write a line of text which is passed as a string to the write() method. Finally, once you have completed writing or reading operation on a file, you need to close the file to avoid resource deadlock by allowing other processes to access the file. To close the connection to a file, you need to call the close() method.

Once you execute the script above, you should see a file “my_file.txt” in the path that you passed to the open() method. The file will contain the following text:

this is the first line of the file

Writing Multiple Lines of Text

You can also write multiple lines of text to a file.  To write multiple lines to a text file, you can create a list that contains all the lines that you want to write to a file. Next, you can iterate through the list using a loop and pass each line to the write() method. Finally, you can close the connection to the file object. Let’s see an example:

file_handler = open("E:/my_file.txt", "w+")
lines = ["This is line1\n", "This is line2\n", "This is line3\n"]
for line in lines:
    file_handler.write(line)
file_handler.close()

Once you execute the above script, you will see the following three lines in your text file:

This is line1
This is line2
This is line3

It is pertinent to mention that the content that existed in your text file before executing the above script will be removed since “w+” permission removes the existing content and writes new content to a file from scratch.

Instead of using a loop that iterates through a list of strings, in order to write multiple lines of text on a text file, you can use the writelines() function to write multiple lines of text. Here is an example:

file_handler = open("E:/my_file.txt", "w+")
lines = ["This is line1\n", "This is line2\n", "This is line3\n"]
file_handler.writelines(lines)
file_handler.close()

The output of the above script will be the same as the previous script and is shown below:

This is line1
This is line2
This is line3

Appending Text at the End of a File

With write permissions, the existed text in a file is removed and is replaced by the new text. However, if you want to add text at the end of the existing text in a file, you can use the append permissions. Look at the following example:

file_handler = open("E:/my_file.txt", "a+")
lines = ["This is line4\n", "This is line5\n", "This is line6\n"]
file_handler.writelines(lines)
file_handler.close()

In the above script, the file “my_file.txt” is opened with “a+” permission which stands for append and read. Once you execute the above script, you will see that your newly added text is appended at the end of the existing text in the “my_file.txt”. You should see the following output:

This is line1
This is line2
This is line3
This is line4
This is line5
This is line6

Reading Text From Files

In this section, you will be reading the “my_file.txt” file that you created in the last section. The file contains the following 6 lines of text:

This is line1
This is line2
This is line3
This is line4
This is line5
This is line6

Like writing, you can read one line from a text file at a time or all the lines at once. Let’s see various ways in which you can read a text file.

Reading Single Line of Text

To read a text file, first, you have to open it with the read permissions. Next, to read a single line of text, you can call the readline() method of the object returned by the open method. The following script returns the first line of text from the “my_file.txt” file.

file_handler = open("E:/my_file.txt", "r+")
print(file_handler.readline())
file_handler.close()

In the output, you should see the first line as shown below:

This is line1

Reading Multiple Lines of Text

To read multiple lines, there are two ways. You can either call the  readline() multiple times as shown below:

file_handler = open("E:/my_file.txt", "r+")

print(file_handler.readline())
print(file_handler.readline())

file_handler.close()

In the above script, the readline() method is called twice, hence, the first two lines from the text file will be read and printed on the console. The output should look like this:

This is line1
This is line2

The other option is to call the readlines() method which returns all the lines in your text document as a list of strings. You can then iterate through the list and print all the lines from your text document on the console. Look at the following example:

file_handler = open("E:/my_file.txt", "r+")
lines = file_handler.readlines()
for line in lines:
    print(line)
file_handler.close()

Here is the output of the above script:

This is line1
This is line2
This is line3
This is line4
This is line5
This is line6

Reading All the Text

Finally, you can read all of the text in a document at once via the read() method. For reference, look at the following example:

file_handler = open("E:/my_file.txt", "r+")
text = file_handler.read()
print(text)
file_handler.close()

In the output, as shown below, you should see all the text from the “my_file.txt” file:

This is line1
This is line2
This is line3
This is line4
This is line5
This is line6