When youopen a file with the name "filename.ext"; you are telling the open() function that your file is in thecurrent 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 thatrelative 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 yourpython script .
There are several other reasons why the FileNotFoundError Errno 2 No such file or directory error can occur:
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.
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.
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.
Use os.listdir() to see the list of files in the current working directory.
Remember to use a raw string literals if your path uses backslashes.
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 calledabsolute 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 calledrelative 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.