Python error [Errno 2]No such file or directory
Problem phenomenon
When reading Python files, the system cannot find the file or directory with the specified path. The core reason can be attributed to the following three points:
- Path misspelled(If case inconsistent, special characters are not escaped)
- Working directory does not match the relative path(Common in IDE or script calling scenarios)
- The file does not actually exist(Including errors in extension or files being moved)
Among them, the second is the most common cause. It mainly means that there are relative paths in the .py file called in the project. However, the results of running in Pycharm may be different from running in the terminal. One error is reported and the other does not report an error.
Quick Solution
1. Use absolute paths
Directly specify the full path to the file (for fixed environments):
with open("/home/user/project/data/") as f: # Linux Example pass
Note that Windows paths need to handle backslash escape (such asr"C:\Users\"
or double backslash).
2. Dynamically get the directory where the script is located (recommended)
pass__file__
Properties locate the real path of the script to avoid interference from working directory:
import os # The parent directory of the current filescript_dir = ((__file__)) # The parent directory of the current file's parent directory (my here is the project directory)project_dir = (((__file__))) # Choose according to your needsfile_path = (script_dir, "data/") # orfile_path = (project_dir, "data/")
This method is particularly reliable in multi-level directory projects.
Other reasons for troubleshooting
1. Verify file path and name
- Check the spelling of the path string (including English colons, slash directions, etc.), for example
data\
In Linux, it needs to be changed todata/
1 - Confirm whether the file extension matches (eg
.txt
and.csv
The difference) - use
()
Function verify whether the path exists:
import os print(("your_file_path")) # returnTrueThe path is valid
2. Understand working directory and relative paths
- When executing the script, the systemCurrent working directoryIt is the starting point of the relative path, not the directory where the script is located 3
- pass
()
Get the current working directory, if it does not match the expectations: - Setting the working directory (debug configuration item) in the IDE (such as VSCode)
- use
()
Dynamically modify the working directory
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.