3

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:
ParentDirectory
ChildDirectory
SubDirectory
If I was inside of ChildDirectory, I would need to save the name ParentDirectory to a certain string... here is some pseudo code:
import os
var = os.path.parent()
print var
On a side note, I am using Python 2.7.6, so I need to be compatible with 2.7.6...

1 Answers1

7

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 -

import os,os.path
curfilePath = os.path.abspath(__file__)

# this will return current directory in which python file resides.
curDir = os.path.abspath(os.path.join(curfilePath, os.pardir))

# this will return parent directory.
parentDir = os.path.abspath(os.path.join(curDir, os.pardir))
sam
  • 1,819
  • 1
  • 18
  • 30
Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176
  • so if the path to the file "c" is /a/b/c and I want to extract "b" ( the parent directory name) , this will work? I think that is what the OP wanted, Not the parent dir. path, but rather it's name. – majorgear Jun 01 '22 at 02:22