When the specified file is not found in the working directory, or the specified path is invalid, the Python programming language throws a
FileNotFoundError/IOError exception. In this article, we will learn how to resolve this exception in Python.
FileNotFoundError/IOError: no such file in directory Error in Python
One of the easiest and obvious ways to solve this issue is to ensure that the file you refer to exists at the path specified or the current working directory. It is also possible that there is a typographical error or typo in the file name or the file path. These two are the most common reasons due to which we end up hitting a
Apart from the ones mentioned above, there are a few other steps to resolve this error.
- If the file we refer to exists in the current working directory, we can use the pre-installed
osmodule to check if the file exists. The
os.listdir()method lists all the files that exist in the specified directory. We can verify the existence of the required file before proceeding with the actual task. The following Python code presents a simple function that we can use for our use case.
import os def file_exists(filename, path = os.getcwd()): """ Check if the specified file exists at the specified directory """ files = os.listdir(path) return filename in files
file_exists() method will return
True if the file is found and
False if not. If no path to a directory is given, the current working directory is considered. The
os.getcwd() method returns the current working directory.
- For file paths, try going for raw strings over plain strings. When plain strings are used to represent a file path, every backslash or
\has to be escaped or prefixed with another backslash. Since
\is an escaping character in Python, it gets ignored. It has to be escaped to fix that. The following Python code depicts the same.
s = r"path\to\file"