python – Why am I getting a FileNotFoundError?

python – Why am I getting a FileNotFoundError?

If the user does not pass the full path to the file (on Unix type systems this means a path that starts with a slash), the path is interpreted relatively to the current working directory. The current working directory usually is the directory in which you started the program. In your case, the file test.rtf must be in the same directory in which you execute the program.

You are obviously performing programming tasks in Python under Mac OS. There, I recommend to work in the terminal (on the command line), i.e. start the terminal, cd to the directory where your input file is located and start the Python script there using the command

$ python

In order to make this work, the directory containing the python executable must be in the PATH, a so-called environment variable that contains directories that are automatically used for searching executables when you enter a command. You should make use of this, because it simplifies daily work greatly. That way, you can simply cd to the directory containing your Python script file and run it.

In any case, if your Python script file and your data input file are not in the same directory, you always have to specify either a relative path between them or you have to use an absolute path for one of them.

A good start would be validating the input. In other words, you can make sure that the user has indeed typed a correct path for a real existing file, like this:

import os
fileName = input(Please enter the name of the file youd like to use.)
while not os.path.isfile(fileName):
    fileName = input(Whoops! No such file! Please enter the name of the file youd like to use.)

This is with a little help from the built in module os, That is a part of the Standard Python Library.

python – Why am I getting a FileNotFoundError?

Is test.rtf located in the same directory youre in when you run this?

If not, youll need to provide the full path to that file.

Suppose its located in

/Users/AshleyStallings/Documents/School Work/Computer Programming/Side Projects/data

In that case youd enter


as your file name

Or it could be in

/Users/AshleyStallings/Documents/School Work/Computer Programming/some_other_folder

In that case youd enter


Leave a Reply

Your email address will not be published. Required fields are marked *