Home > Backend Development > Python Tutorial > The correct way for Python to get the directory where the script is located

The correct way for Python to get the directory where the script is located

大家讲道理
Release: 2016-11-09 11:12:37
Original
1208 people have browsed it

C:test
  [dir] getpath
    [file] path.py
    [dir]  sub
      [file] sub_path.py
Copy after login

For example,

C: There is also a directory named sub in the test directory;

C: There is getpath.py in the test directory, sub_path.py in the sub directory, getpath.py calls sub_path.py;

We Execute getpath.py under C:test. if we were If sys.path[0] is used in sub_path.py, what is actually obtained is the directory path "C:test" where getpath.py is located, because Python virtual The machine starts execution from getpath.py. If you want to get the path of sub_path.py, then you have to do this:
os.path.split(os.path.realpath(__file__))[0]

Verification:

Then we execute python getpath/path under C:test. py, at this time, the values ​​corresponding to various usages in sub_path.py are actually:
os.getcwd() "C:test", which takes the starting execution directory
sys.path[0] or sys.argv[0 ] "C:testgetpath", takes the directory where the initially executed script is located
os.path.split(os.path.realpath(__file__))[0] "C:testgetpathsub", takes the directory where __file__ is located The directory where the file sub_path.py is located


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template