How do I fix FileNotFoundError?

Question:
How do I fix this error:
FileNotFoundError: [Errno 2] No such file or directory: ‘List animals.txt’

Repl link:
https://replit.com/@Hadl4/Practice-2

	if promptSelection in validPromptSelections[:3]:
		file2 = open('List animals.txt', 'r')
		print(random.choice(file2.read()))

I’m relatively inexperienced and am trying to select a random animal from the text file and print it.

There has already been a question about this but the solution is not clear.

There is no file named List animals.txt in your repl, this is indicated by an error. You can either create a file with that name, or change your code so that it doesn’t read the file List animals.txt , but List game suggestions.txt (such a file exists in your repl).

It is also not recommended to use spaces in the names of files and folders. Use underscores or dashes instead.

3 Likes

I don’t understand what you mean by there is no file in my repl

What @KAlexK is saying is that the file you are trying to access does not exist, rather there is another similarly named file which isn’t being read. You can rename the file accordingly or change the code to fit the filename.

1 Like

But it does exist. Here’s a screenshot:
ss

Hey @Hadl4!

This file exists locally on your computer, however the Repl itself cannot access the contents of you computer; try uploading the file to the Repl.

2 Likes

How might I do that?

Additionally, those files have dashes in their names where your code assumes there is a space.

1 Like

I changed the spaces to dashes after Alex’s feedback.

In the top-left corner (below the search bar), there is a three dots icon, click on it and you will see a drop-down menu. Click Upload file and select a file.

1 Like

Alternatively, you can drag and drop the files from your computer’s file explorer into Replit’s Files pane on the left of your Repl.

2 Likes

Cool, I will try that and see how it goes.

2 Likes

It has worked, although instead of printing a random word from the file, it is printing a random letter from the file. How do I fix that?

	if promptSelection in validPromptSelections[:3]:
		animalsFile = open('List-animals.txt', 'r')
		print(random.choice(animalsFile.read()))
1 Like

To do this, you can do this:

if promptSelection in validPromptSelections[:3]:
    animalsFile = open('List-animals.txt', 'r')
    print(random.choice(animalsFile.read().split(' ')))

This will split the string into a list of words.
Also, don’t forget to do animalsFile.close() when you are done using the file.

5 Likes

Small improvements:

if promptSelection in validPromptSelections[:3]:
    with open('List-animals.txt') as file:
        print(random.choice(file.read().split()))
3 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.