FileNotFoundError: [Errno 2] No such file or directory
When you open a file with the name "filename.ext"; you are telling the open() function that your file is in the current working directory . This is called a relative path.
In the above code, you are not giving the full path to a file to the open() function, just its name - a relative path. The error "FileNotFoundError: [Errno 2] No such file or directory" is telling you that there is no file of that name in the working directory. So, try using the exact, or absolute path.
In the above code, all of the information needed to locate the file is contained in the path string - absolute path.
It's a common misconception that relative path is relative to the location of the python script, but this is not true. Relative file paths are always relative to the current working directory, and the current working directory doesn't have to be the location of your python script .
There are several other reasons why the FileNotFoundError Errno 2 No such file or directory error can occur:
- Misspelled filename
There may be times when your filename will have been misspelled. In such a case, the file you specified will not exist in the current directory. So, recheck your filename.
- Accidentally using escape sequences in a file path
Above code throws error because the '\n' in 'Users\neo' is a line break character.
To avoid making this mistake, remember to use raw string literals for file paths.
- Forgetting that Windows doesn't display file extensions
Since Windows doesn't display known file extensions, sometimes when you think your file is named "myFile.yaml", it's actually named "myFile.yaml.yaml". So, double-check your file's extension.
How to avoid FileNotFoundError: [Errno 2] No such file or directory?
- Make sure the file exists
Use os.listdir() to see the list of files in the current working directory.
- Use an absolute path to open the file
- Raw String Literals
Remember to use a raw string literals if your path uses backslashes.
- Change the current working directory before opening the file
Relative Path Vs. Absolute Path
A file is identified by its path through the file system. A path is either relative or absolute. The path with reference to root directory is called absolute path . An absolute path always contains the root element and the complete directory list required to locate the file. For example: "C:\path\to\your\filename.ext". All of the information needed to locate the file is contained in the path string. The path with reference to current directory is called relative path . A relative path needs to be combined with another path in order to access a file. For example: "your\filename.ext" is a relative path. Without more information, a program cannot reliably locate the joe/foo directory in the file system.