Python Gets the current directory path and ancestor path __python

Source: Internet
Author: User

When using Python, you will always encounter the use of path switching, such as the test.py under folder test to invoke the Data.txt file under the Data folder:

.
└──folder
    ├──data
    │   └──data.txt
    └──test
        └──test.py

A method can be added to the data file __init__.py then import data in the test.py can invoke Data.txt file;

Another way to manipulate the directory structure with the help of the Python OS module is to use the following:

Import OS

print ' * * * Get current directory * * *
os.getcwd ()
print Os.path.abspath (Os.path.dirname (__file__))

print ' * * * get Superior Directory * * * *
Os.path.abspath (Os.path.dirname (Os.path.dirname (__file__))
Print Os.path.abspath (Os.path.dirname (OS.GETCWD))
print Os.path.abspath (Os.path.join (), "..."

) print ' * * * gets on top of the directory * * *
Os.path.abspath (Os.path.join (OS.GETCWD), ". /.."))

The output results are:

Get current Directory * * */workspace/demo/folder/test/workspace/demo/folder/test * * *
access to

Superior directory * * *
Workspace/demo/folder
/workspace/demo/folder
/workspace/demo/folder

* * * access to Superior directory * * * *
Workspace/demo
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.