Python program to find longest word from file.

Write a python program to find longest word from text file with Practical Example

Program Logic:

  • Open text file say ‘name.txt’ in read mode using open function
  • Pass file name and access mode to open function
  • Read the whole content of text file using read function and store it in another variable say ‘str’
  • Use split function on str object and store words in variable say ‘words’
  • Find maximum word from words using len method
  • Iterate through word by word using for loop
  • Use if loop within for loop to check the maximum length of word
  • Store maximum length of word in variable say ‘longest_word’
  • Display longst_word using print function

Below is implementation code/Source code

fin = open("name.txt","r")
str =
words = str.split()
max_len = len(max(words, key=len))
for word in words:
    if len(word)==max_len:
        longest_word =word

Below is Output:


Below is Snapshot of Executable code with output

Below is name.txt file