Find the Longest Word in a Text File in Python

In this tutorial, we will learn how to Find the Longest Words in a Text File in Python. Using file handlers we will learn how to Find the Longest Words in a Text File in Python.


The following represents the syntax of the open() method:

where the open() method takes two parameters as

  • The first parameter takes the path of the file
  • The second parameter takes the modes of the file.

Modes of the file are:

  1. read mode(“r”)-opens the file in read mode
  2. write mode(“w”)-opens the file in write mode in the existing file
  3. override(“w+”)-opens the new file in writing mode.

Let’s have a look at its usage below as:

#Opening the file in reading mode

print("Data read")

#Opening the file in writing mode

print("Data written into the file")

#Opening the file in "W+" mode

print("Data written into the new file")


Data read
Data written into the file
Data written into the new file

In the above program, we opened the file in different ways of modes. In the first line, we opened the file in reading mode. As the second line of our program, we opened the file in writing mode. Next, we created a new file in writing mode using the “w+” mode. So, as per the program, the text file we considered is “file.txt” for the input. Finally, we closed the file using the close() method after every usage. Now let’s have a glance at finding the longest word in a text file in Python:



for i in d:


In the above script, first, we opened the file and stored its object contents in “d”¬†by splitting with spaces using the split() method. Next, we considered two empty lists for finding the longest keyword in our text file. Using looping statements we stored the keyword contents in the “m” list and its length in the “l” list. ¬†Finally using the max and index built-in methods of lists we solved our problem.

For reference

Leave a Reply

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