SoFunction
Updated on 2024-11-10

Python relative path error: "No such file or directory"' causes and solutions

Python relative path error: "No such file or directory"' causes and solutions

If you take relative paths that aren't in the main file, you may have relative path problems:"No such file or directory"
Because of python's relative paths, they are relative to the main file.
The following directory structure:

| -- 
     | -- 
     | -- 
| -- 

is the main document.
referenced in Use relative paths.
If you use. maybe. . As opposed toSo with"./"relative to is in the same directory.
. refers to the folder where the current file is located.. . Refers to the previous directory of the current file.

Add: Solution for "FileNotFoundError: [Errno 2] No such file or directory" in python.

What we encountered when running Python code with vscode

图1

I. Causes of emergence:

This is due to the fact that in Vscode, paths in python are located relative to the working directory. So in a multi-level directory situation, if you don't set an absolute path, you won't be able to find the appropriate file.

II. Solutions:

First, open the Settings button in the bottom left corner, type python dir in the box, enter, find the python column, open it, and check "Execute In File Dir". Or type "": true in the box.

Below:

图2

Run results:

图3

Everything is fine and there are no more hints from earlier.

to this article on Python relative path problem: "No such file or directory" 'cause and solution to this article, more related python No such file or directory content please search for my previous articles or continue to browse the following related articles I hope you will support me in the future more!