Exercise 59

Write a Python program that displays the longest word found in a text file.

Solution

# opening the existing file in read mod
f = open("monFichier.txt", 'r')

# getting the file content
content = f.read()

# converting the content to a list
L = content.split()

# creating of an empty string which will take the value of the longest word
motMax = ""

# browse the elements of the list while comparing their lengths with this one
for mot in L:
if(len(mot))>= len(motMax):
motMax = mot
print("The longest word in the file is : ", motMax)
Younes Derfoufi
my-courses.net

Leave a Reply