Python file program to find the longest word in a file

In this python file program, we will find the longest word in a file. Let’s consider we have readcontent.txt file with the below content. We will find the longest word in a file with the help of the below-given steps.

				
					# ReadContent.txt
This is Python Programming Language
Its very easy to learn to and 
Best language for beginners
				
			
Steps to solve the program
  1. Create a varibale to store the longest word and assign ita value equal to empty string.
  2. Create another variable to store its length and assign its value equal to 0.
  3. Read the file using open(“readcontent.txt,”r“).
  4. Read the using read().
  5. Convert the data into words using split().
  6. Use a for loop to iterate over the words.
  7. Use an if-else statement to check whether the length of the word is greater than max_len.
  8. If yes then assign the length of that word to max_len and the word to max_word.
  9. After the loop is complete then print the output.
				
					# Create variables
max_word = ''
max_len = 0
# Read file with read mode
with open("ReadContent.txt", "r") as file:
    file_data = file.read()
    # Convert data into words
    word_list = file_data.split()
    # Iterate over words
    for word in word_list:
    # Check for word with maximum length
        if len(word) > max_len:
            max_len = len(word)
            max_word = word
        else:
            continue
# Print the result
print("Max length word :", max_
				
			

Output :

Max length word : Programming
Max length : 11

 

 

read a file line by line and store it in a list.

get the count of a specific word in a file.

Leave a Comment