Unable to open text file using

I am using this program

#Program to find most used word

name = input('Enter a file:') #Ask user for input file,
handle = open(name) #assign a handle to the file name and open file

counts = dict() #make an empty dictionary
for line in handle: #Look at each line
    words = line.split() #This splits the line
    for word in words: #Look at each word
    #If a word exists get the number of words, else default value is zeo
        counts[word] = counts.get(word,0) + 1 # +1 is added else default value of found word starts with 0

bigcount = None
bigword = None

for word,count in counts.items(): #Looking at items (items are key and its value)
    if bigcount is None or count > bigcount: #If no word is found or if word count is bigger than previous count
        bigword = word #Assign new winning word
        bigcount = count #Assign new winning count

print (bigword,bigcount) #Print key, value

and I am getting this error when I run it in terminal

[pytest]$ py test.py
Enter a file:sonnets.txt
Traceback (most recent call last):
  File "test.py", line 3, in <module>
    name = input('Enter a file:') #Ask user for input file,
  File "<string>", line 1, in <module>
NameError: name 'sonnets' is not defined

What am I doing wrong here???

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

1 Like

To answer your question,

It looks like the first line of sonnets.txt is empty. Is this correct?

I just figured this one out…

Previously the command that I wrote on terminal wasn’t pointing the bash towards the latest python. I had a feeling that this was the problem. So I went ahead and wrote this

[pytest]$ python --version
Python 2.7.16
[pytest]$ alias python=/usr/local/bin/python3
[pytest]$ python --version
Python 3.8.4

and got this as a reply when I ran the program

[pytest]$ py test.py
Enter a file:sonnets.txt
the 356

Thanks a lot for helping me with the code highlighting syntax. Very helpful.

1 Like