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
- Create a varibale to store the longest word and assign ita value equal to empty string.
- Create another variable to store its length and assign its value equal to 0.
- Read the file using open(“readcontent.txt,”r“).
- Read the using read().
- Convert the data into words using split().
- Use a for loop to iterate over the words.
- Use an if-else statement to check whether the length of the word is greater than max_len.
- If yes then assign the length of that word to max_len and the word to max_word.
- 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