Home >Backend Development >Python Tutorial >How to solve the pitfalls of os.path.exits() in python

How to solve the pitfalls of os.path.exits() in python

WBOY
WBOYforward
2023-05-16 17:58:271128browse

Question

Sometimes we often see similar code:

assert os.path.isdir(path_model_dir)
assert os.path.exits(path_model_dir)

If you fill in a relative path as path_model_dir, it will have disastrous consequences. We need to pay attention to the following elements:

  • The os.path.exists() method does not directly use the path in sys.path to find the file. It calls the operating system Interface to check if a given path exists.

  • When using a relative path, Python will first interpret it as relative to the current working directory. Normally, the current working directory of an interactive interpreter is the directory from which the interpreter was started.

The above two paragraphs explain that if you fill in a relative path, the relative path mentioned here is a relative path relative to the current file or a relative path relative to the interpreter. Is it relative to running the interpreter, debugging the interpreter, or is it relative to the relative path in the command line? I once edited code in the same editor, and it could be run directly when running, but it kept reporting errors when debugging. Later I found that the relative paths of the debugging interpreter and the running interpreter in the same editor were different (surprise) !).

And the os.path.exists() method does not directly use the path in sys.path to find files, nor does it use the environment variables in ~/.bashrc to find files, it only uses relative paths. and absolute path to find the file.

Suggestions

There are two suggestions. The core point is to use absolute paths.

  • Direct absolute path to hard-coded string

  • (Recommended) Use __file__ to splice the absolute path relative to the script file

Some people ask what the path added in sys.path.append(path) is used for. In fact, the path added here is mainly used to import the import package. That is, if you want to add additional directories to Python's module search path, you can add those directories to the sys.path list. This will cause Python to automatically include these directories when searching for modules. Note, however, that this method is used when Python imports the module, not when calling the os.path.exists() method.

The above is the detailed content of How to solve the pitfalls of os.path.exits() in python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete