python get current directory path and parent path

When using python, you will always encounter the use of path switching. For example, if you want to switch from the folder testtest.pyCall the data folderdata.txtdocument:

.
└── folder
    ├── data
    │   └── data.txt
    └── test
        └── test.py
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

A method can be added under the data file__init__.pythen intest.pymiddleimport datayou can calldata.txtdocument;

Another method can use the method of python os module to operate the directory structure. Let's talk about the use of this method:

import os

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

print  '***Get the parent directory***' 
print  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( os .getcwd(), ".." ))

print  '***Get the parent directory***' 
print  os .path.abspath( os .path.join( os .getcwd(), "../.." ))
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

The output is:

** * Get current directory ** *
/workspace/demo/folder/test
/workspace/demo/folder/test

** * Get the parent directory ** *
/workspace/demo/folder
/workspace/demo/folder
/workspace/demo/folder

** * Get the parent directory ** *
/workspace/demo
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

Related: python get current directory path and parent path