Python – Finding the longest word in a text file error

I am trying to find the longest word in a text file and it keeps on saying: ValueError: max() arg is an empty sequence

def find_longest_word(filename):
    with open(filename,'r+') as f:
        words =
        max_len_word = max(words,key=len)   
        print('maximum length word in file :',max_len_word)
        print('length is : ',max_len_word)

What did I do wrong?


This should work for you:

from functools import reduce

def find_longest_word(filename):
    f = open(filename, "r")
    s = [y for x in f.readlines() for y in x.split()]
    longest_word = reduce(lambda x, y: y if len(x) < len(y) else x, s, "")
    print("The longest word is", longest_word, "and it is", len(longest_word),"characters long")

    return longest_word