How to Fix FileNotFoundError: No Such File or Directory

FileNotFoundError: No Such File or Directory error occurs when you are trying to access a file or folder that does not exist.

One of the reasons for the error is that there might be times when your files won’t exist in the current directory.

Visual representation

Diagram of How to Fix FileNotFoundError: No Such File or Directory Error in Python

How to fix this error?

To fix the error, check that you are referring to the right file or folder in your program.

try:
  with open("app.txt", "r") as file:
  contents = file.read()

except FileNotFoundError:
  print("File not found.")

In this code example, if the file “app.txt” is not found, the exception FileNotFoundError will be raised, and the “File not found.” error will be printed.

Alternate way

You can also use the “os.listdir()” method to check all the files in the directory. 

Ensure you’re in the directory you think you’re in with “os.getcwd()” (if you launch your code from an IDE, you may be in a different directory).

1 thought on “How to Fix FileNotFoundError: No Such File or Directory”

  1. Such a good explanation😍😍😍
    I have got the error of no such file found in python but after reading this content I correct my code and my error is resolved now
    Thanks for the great explanation

    Reply

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.