Sorting contents of a text file using a Python program

In this tutorial, we will learn a method for sorting the contents of a text file using a Python program. Here, we will sort the contents of a file in ascending order i.e. alphabetically. That is, we will sort the contents similar to the way in which words are listed in a dictionary. Today, we will get to know how to open a file, a method to sort the contents of an opened file and a Python program that will create another file having the same content in sorted order.

Opening a file for sorting operation

To sort the contents of a file, firstly we need to open the file in ‘read’ mode. Here, we take the file ‘sample.txt’ for simplicity. But, we can also take the name of the file from the user as an input. After this, we will open the specific file using statement given below-

file = open(“filename.extension”)

For example –> file = open(“sample.txt”)

Two cases arise after the execution of this statement-

  • Case 1- The file with this name is not present in the directory where the program is stored. To resolve this issue, we can save the file in the same directory or we can give the complete path of the file in the statement.
  • Case 2- The file with this name is present. So, we can proceed to perform the sorting operation.

Method for sorting contents of a text file in Python

After opening the file in ‘read’ mode, we have to sort the contents of that file. For sorting, firstly we have to fetch the contents of the file. So, we will follow the below steps to fetch the contents-

  1. Open the file in ‘read’ mode.
  2. Declare a Python list ‘words’.
  3. Fetch a single line from the file.
  4. Split on the line using function ‘split()’ and store it in a temporary Python list.
  5. Finally, append each word in the temporary list to Python list ‘words’.
  6. Go to step 2 and repeat the steps until the end-of-file (EOF) is reached.

So, we have stored all the words in the Python list ‘words’. Now, we will use an in-built function ‘sort()’ to sort the contents in ascending order. The statement to sort the contents using ‘sort()’ function is-


Finally, the Python list ‘words’ contains the sorted contents.

Python program for sorting contents of a file

Now, we will see a Python program to sort the contents of a file. Firstly, we call the function ‘sorting’ and pass the name of the file i.e. ‘sample.txt’ and open it in the ‘read’ mode. Then we fetch the contents of the file and sort the words in ascending order. Finally, we store the sorted contents in another file ‘result.txt’. The Python program is given below-

def sorting(filename):
  infile = open(filename)
  words = []
  for line in infile:
    temp = line.split()
    for i in temp:
  outfile = open("result.txt", "w")
  for i in words:
    outfile.writelines(" ")

Finally, we store the sorted contents in a file ‘result.txt’.

Python program output

For the execution of the above program, we need a file as input. Here, the file ‘sample.txt’ is taken as input. Also, we can take the name of the file from the user.

The contents of the input file ‘sample.txt’ is-


The Python program is executed using the following command-

[email protected]:~/python$ python3

Finally, we get the sorted contents in file ‘result.txt’ after sorting operation-


The contents in file ‘result.txt’ are sorted alphabetically.

Also read: Create PDF file from .txt file in Python

7 responses to “Sorting contents of a text file using a Python program”

  1. Harshi says:

    When I try to run program it’s showing invalid syntax at first line which is
    def sorting(filename.txt)
    I don’t know what’s error plz help

    • Saruque Ahamed Mollick says:

      You should use “filename.txt” not filename.txt
      I hope you understand the value of the quotation marks. If you still receive the same problem feel free to reply here.

      • Anonymous says:

        If u give “filename.txt” in def parameter, then the variable filename inside the def becomes useless. The variable filename in def(filename) can be altered whereas in def(“filename.txt”) the parameter is only “filename.txt”. Hope u uderstood

    • Anonymous says:

      In the parameter bracket u cannot give any other symbol other than underscore (_). So if u put a dot it is a syntax error.
      Try def sorting(filename). The .txt is used only for opening and not is statement commands. Hope u understood

  2. harshi says:

    i tried this and also tried to do it by mentioning path but still its showing syntax error at first line i dont know where the mistake is and i should do this only by using thonny IDE need some help with this

  3. nathan says:

    what folder should I put the filename.txt file to so the program can read it?

  4. nathan says:

    originally it gave me an error in (“filename”) until I removed quotes , it won’t let me run it though

Leave a Reply

Your email address will not be published. Required fields are marked *