Get Parent path value (bad design) Help

Larry Bates lbates at swamisoft.com
Mon Aug 30 16:44:51 CEST 2004


I think what you want is:

import os
pathname=os.getcwd()
parentpath=os.sep.join(pathname.split(os.sep)[:-1])
sys.path.append(parentpath) #append the path back to sys.path

This is shorter and portable.

HTH,
Larry Bates
Syscon, INc.



"Golawala, Moiz M (GE Infrastructure)" <Moiz.Golawala at ge.com> wrote in
message news:mailman.2601.1093875943.5135.python-list at python.org...
Hi all,

What I am trying to do is write some generic code where I can get the path
of the parent directory. for example if current working directory is
'Z:\\dirA\\Parent\\Child'

I want to get a string which up like 'Z:\\dirA\\Parent'
Then I do a sys.path.append('Z:\\dirA\\Parent')

The code I have written below does all this.. but I have a feeling there is
a better way to do this.. Please can someone help me.

import os
import sys
pathname = os.getcwd()
pathString = ''
pathList = pathname.split("\\")

pathList.pop()  # removes the child
lastItem = pathList.pop() #remove to the parent, will be added back later.
counter = 0
while counter != len(pathList):  #build up the path with items in the list
    pathString = pathString + pathList[counter] + "\\\\"
    counter +=1
pathString = pathString + lastItem #add parent back to the built up path
sys.path.append(pathString) #append the path back to sys.path


Thanks,
Moiz Golawala





More information about the Python-list mailing list