Dylan Hewitt
Dylan Hewitt

Reputation: 3

NameError when trying to use file operations

So im trying to write a simple program in python 3, that searchs a file and conuts the frequency of specific words that ive specified in a list. However when I try to define a variable as my file, I get a NameError saying the variable im trying to use isnt defined. This may be a poor explanation but heres my code and the error:

def file_write():
    f1 = open('Tutorial5.txt', 'w+') 

def file_read():
    f1 = open('Tutorial5.txt', 'r')

def count_stpwrds():
    stpwrds = ['about','above','across','after','afterwards','again','against','all','almost','alone','along','already','also','although','among','amongst','amoungst','amount','an','and','another','any','anyone','anything','anyway','anywhere']
    frequency = dict()
    for line in f1:
        words = line.split()
    for aword in words:``
        if aword in stpwrds:
            if aword not in frequency:
                frequency[aword] = 1
            else:
                frequency[aword] += 1
    print(frequency)

def main():
    file_write()
    file_read()
    count_stpwrds()

if __name__ == "__main__":
    main()
    

When I try to run in vscode, I get:

Traceback (most recent call last):
      File "c:/Users/User/Desktop/School/COMP 1005 Code/Tutorials/Tut 5.py", line 26, in <module>   
        main()
      File "c:/Users/User/Desktop/School/COMP 1005 Code/Tutorials/Tut 5.py", line 23, in main       
        count_stpwrds()
      File "c:/Users/User/Desktop/School/COMP 1005 Code/Tutorials/Tut 5.py", line 10, in count_stpwrds
        for line in f1:
    NameError: name 'f1' is not defined

Could someone please explain to me what I am doing wrong? Any help would be greatly appreciated!

Upvotes: 0

Views: 118

Answers (1)

paxdiablo
paxdiablo

Reputation: 881293

The f1 variable name s bound to the return values from open in your two functions, but that binding disappears when the functions exit. That means f1 does not "exist" in count_stpwrds().

A seemingly easy way to fix this would be to make the variable a global but I'm not going to tell you how to do that because there's a better way :-)

What you should do is to simply return the file handle from the functions that open files, and pass that to functions that need it, something like:

def file_write():
    return open('Tutorial5.txt', 'w+') 

def file_read():
    return open('Tutorial5.txt', 'r')

def count_stpwrds(fileHandle):
    # Blah blah blah

    for line in fileHandle:
        words = line.split()

    # Blah blah blah

def main():
    f1 = file_write()
    f1 = file_read()
    count_stpwrds(f1)

Upvotes: 1

Related Questions