How to generalize the file function to open as many text files as provided in parameter?

Viewed 42

I want to generalize my following code to take as many files in parameters without hardcoding, like f1 and f2 are here. How can i do that? Here is my code.

def wordFreq(f1, f2):
    f1 = open(f1, 'r')  
    f2 = open(f2, 'r')
    file_list = [f1, f2]  
    num_files = len(file_list) 
    wordFreq = {} 

    .....
    .....

    return wordFreq

print(wordFreq('file1.txt','file2.txt'))
1 Answers

You want *args

def word_freq(*files):
    file_list = [open(file, 'r') for file in files]
    ...
Related