Python gets the correct method for the directory where the script is located

Source: Internet
Author: User
C:test  [dir] getpath    [file] path.py    [dir]  sub      [file] sub_path.py

Like what

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

C:\test directory under the Getpath.py,sub directory has sub_path.py,getpath.py call sub_path.py;

We execute getpath.py under the C:\test. If we use sys.path[0 in sub_path.py, we actually get the directory path "C:\test" where the getpath.py is located, because the Python virtual machine is executed from the beginning of the getpath.py. If you want to get the path to the sub_path.py, you get this:
Os.path.split (Os.path.realpath (__file__)) [0]

Verify:

Then we execute the python getpath/path.py below the C:\test, at which point the values corresponding to each usage in sub_path.py are actually:
OS.GETCWD () "C:\test", which takes the starting execution directory
Sys.path[0] or sys.argv[0] "C:\test\getpath", which is the directory where the script was executed initially
Os.path.split (Os.path.realpath (__file__)) [0] "C:\test\getpath\sub", which is the directory where __file__ files sub_path.py

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.