Timon
Timon

Reputation: 327

How to write a function that takes in the name of a file as the argument in Python?

I need to create a function return_exactly_one(file_name) that takes in the name of a text file as the argument, opens the text file, and returns a list that only contains words that occurred exactly once in the text file. My file is test.txt, but I have trouble about the argument of the function. I'm not allowed to take test.txt as the argument, because it's an invalid variable. And when I call the function, what should I put into the parenthesis? How to solve it? Thanks. My code is as follows.

import string

def return_exactly_one(test):
    test = open("test.txt", "r")
    text = test.read()
    test.close()

    for e in string.punctuation:
        if e in text:
            text = text.replace(e, "")
            text_list = text.split()
            word_count_dict = {}
    for word in text_list:
        if word in word_count_dict:
            word_count_dict[word] +=1
        else:
            word_count_dict[word] = 1

    once_list = []
    for key, val in word_count_dict.items():
        if val == 1:
            once_list.append(key)

    return once_list

 print(__name__)
 if __name__ == "__main__":

    print("A list that only contains items that occurred exactly once in the text file is:\n{}.".format(return_exactly_one(test)))

Upvotes: 0

Views: 18935

Answers (2)

Ayush
Ayush

Reputation: 1620

I'm not sure what's preventing you from doing that. You need only store the filename as a string and pass the string to the function. So for example, you could take the filename as input like so:

file_name = input("Enter the name of the file:")

And then call the function with the file name like so:

return_exactly_one(file_name)

Also, inside the function you'd open it this way:

test = open(file_name, "r")
# Notice, no quotes, it's a variable here, not a string

Upvotes: 0

ruby
ruby

Reputation: 381

Your function should take a string filename as a parameter, like this:

def return_exactly_one(filename):
    test = open(filename, "r")
    ...

and then you would call the function like:

return_exactly_one("test.txt")

Upvotes: 4

Related Questions