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 = fin.read()
words = str.split()
max_len = len(max(words, key=len))
for word in words:
if len(word)==max_len:
longest_word =word
print(longest_word)
Below is Output:
Sumedh
Below is Snapshot of Executable code with output


Below is name.txt file


<