I am having issues with Python For Everyone Section 1.8 and terminal usage

Viewed 44

I am relearning the fine points of Python and going through the Python for Everybody Book.

I am currently stuck on section 1.8 involving the use of the Terminal. It is asking me to use a Python Program in the Terminal to scan the textfile. The book has provided the python code and textfile that I should use for this section. I have created both the Python program and the textfile and have them both on my desktop and therefore in the same file.

The Python Program in the file is listed below and is named words.py.

name = input('Enter file:')
handle = open(name, 'r')
counts = dict()

for line in handle:
    words = line.split()
    for word in words:
        counts[word] = counts.get(word, 0) + 1

bigcount = None
bigword = None
for word, count in list(counts.items()):
    if bigcount is None or count > bigcount:
        bigword = word
        bigcount = count

print(bigword, bigcount)

The textfile that I have created has the text below and is named clowntext.txt

the clown ran after the car and the car ran into the tent
and the tent fell down on the clown and the car 

Now again the files clowntext.txt and words.py are in the same folder on my desktop. Therefore why is the terminal advising me that there is no file of the name I specify when I run the Python program within my terminal? The entire block of what I see within my terminal is below in code.

Last login: Mon Nov 29 06:33:44 on ttys000
(base) wayneshaw@Waynes-MacBook-Air ~ % python Desktop/words.py
Enter file:clowntext.txt
Traceback (most recent call last):
  File "/Users/wayneshaw/Desktop/words.py", line 2, in <module>
    handle = open(name, 'r') 
FileNotFoundError: [Errno 2] No such file or directory: 'clowntext.txt'
1 Answers

Your program is looking for the file in the current directory, ~, but clowntext.txt is in ~/Desktop.

While the program is in the same folder as your input file, you started your program from a different folder (your input file is in ~/Desktop, but you started it from ~), and the program is not searching for a file from the folder in which the program is located (~/Desktop), but from the folder from which the program was started (~).

You could either give your program a full path, Desktop/clowntext.txt, or move clowntext.txt to ~.

Related