Reputation: 339
How would you read over two or more files, and determine the longest in a file?
I tried doing something like this, but because of the for loop it will print the longest word in each file. How I can compare both files and print only one output?
for word in filenames:
with open(word) as w:
x = w.read()
y = max(x.split(), key = len)
if word > y:
print '\nLongest Word:', y
else:
pass
Upvotes: 1
Views: 50
Reputation: 8061
You can do this, to keep the longest word in a variable and then print it at the end:
longest_word = ''
for word in filenames:
with open(word) as w:
x = w.read()
y = max(x.split(), key = len)
if len(y) > len(longest_word):
longest_word = y
print '\nLongest Word:', longest_word
Upvotes: 1