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:

–>f=open(“path”,”mode”)
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

f=open("file.txt","r")
d=f.read()
print("Data read")
f.close()

#Opening the file in writing mode

f=open("file.txt","w")
d=f.write("Hi")
print("Data written into the file")
f.close()

#Opening the file in "W+" mode

f=open("new.txt","w+")
d=f.read()
print("Data written into the new file")
f.close()

Output:

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:

Example:

f=open("file.txt","r")
d=f.read().split()
f.close()
l,m=[],[]

for i in d:
    m.append(i)
    l.append(len(i))

f=l.index(max(l))
print(m[f])

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.