Read and write the content of a file backward in Python

Read and write the content of a file backward in Python

This post will show you how to read a file in backward in Python and also how to write the content to a different file.

We can read the lines and print the lines in reverse order to a different file. Or, we can reverse the content of the file and print it.

We will learn different ways with examples to read and write the content in reverse.

Method 1: Read and write the file lines in backward:

Let’s try to read the lines of a file and write these lines in backward to another file. We will use the following algorithm in the program:

  • Open the file and read the lines of the file to a list.
  • Reverse the list content.
  • Open the output file and write the lines of the list.

Below is the complete program:

with open('input.txt') as input_file:
    file_content = input_file.readlines()

reverse_file_content = file_content[::-1]

with open('out.txt', 'w') as output_file:
    output_file.writelines(reverse_file_content)
  • This program is reading the content from the file input.txt and writing the content to out.txt.
  • We are not providing any mode while opening the input.txt file. It will open it in read mode by default.
  • The readlines() method returns a list holding the lines of file as a list item. The return value is stored in the variable file_content
  • The next line is reversing the content of file_content list. It uses [::-1] to reverse the lines in the list.
  • The second with block is writing these lines to the out.txt file. We are using the writelines method to write these lines of the list to the file.

For example, if the input.txt file contains the following content:

hello world
hello universe
hello !!

It will write the below content to out.txt:

hello !!
hello universe
hello world

Method 2: Read the content and write it in reverse:

Instead of reading the lines to a list, we can also use read() method to read the whole content of a file and reverse it. Let me change the above program to use read():

with open('input.txt') as input_file:
    file_content = input_file.read()

reverse_file_content = file_content[::-1]

with open('out.txt', 'w') as output_file:
    output_file.writelines(reverse_file_content)

I am only changing the readlines() method to read() in this example. If you run this, it will write the following content to out.txt:

!! olleh
esrevinu olleh
dlrow olleh

As you can see here, the whole content of the file is changed.

You might also like: