This question already has an answer here:
I have a program in python that prints out information about the file system... I need to know to save the name of the parent directory to a variable...
For example, if a tiny bit of the file system looked like this:
If I was inside of ChildDirectory, I would need to save the name ParentDirectory to a certain string... here is some pseudo code:
var = os.path.parent()
On a side note, I am using Python 2.7.6, so I need to be compatible with 2.7.6...
Best How To :
You can get the complete file path for the script resides using
__file__ variable , then you can use
os.path.abspath() to get the absolute path of your file , and then use
os.path.join() along with your current path , and the parent directory descriptor -
.. in most operating systems , but you can use os.pardir (to get that from python , so that it is truly platform independent) and then again get its absolute path to get the complete path of current directory, then use it with same logic again to get its parent directory.
Example code -
curfilePath = os.path.abspath(__file__)
curDir = os.path.abspath(os.path.join(curfilePath,os.pardir)) # this will return current directory in which python file resides.
parentDir = os.path.abspath(os.path.join(curDir,os.pardir)) # this will return parent directory.