Hanros94
Hanros94

Reputation: 13

Counting words in a file

I am trying to write a function which will count the numbers of words in a file. But for some reason when I run it an error occurs:

def wc(filename):
    """returns the number of words in file filename."""
    f = open(filename, 'r')
    lines = f.readlines()
    f.close()
    total = 0
    for line in lines:
        words = line.split()
        n = len(words)
        total = total + int(n)
    return total

The error says filename is undefined.

The file name is alice. When I type in wc(alice.txt) in the console on the bottom right hand side, it returns:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'alice' is not defined

I have saved the file on a usb drive along with the Python file.

Upvotes: 0

Views: 739

Answers (2)

Blckknght
Blckknght

Reputation: 104722

I believe the issue is how you are calling the function. If you use:

wc(alice.txt)

You'll probably get an error because alice.txt tells python to look for an object named alice in your current environment and then try to look up a txt attribute on it. If no such object or attribute exist, you'll get an error.

What you want to do instead is pass alice.txt to your function as a string. To do this you need to put it in quotation marks:

wc("alice.txt")

Upvotes: 2

Siva Cn
Siva Cn

Reputation: 947

def wc(filename):
    ## Your stuff here

This function takes one arguement, which is filename So, you are required to pass filename to this function along with relative or absolute path

Suppose your filename is test_input.txt and which is in current working directory,

print wc('test_input.txt')

if your file is not in the current working directory

print wc('/path/to/your/file/test_input.txt')

Upvotes: 0

Related Questions