faqts : Computers : Programming : Languages : Python : Snippets

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

1 of 1 people (100%) answered Yes

Entry

Normalizing pathname

Jul 5th, 2000 09:59
Nathan Wallace, Hans Nowak, Snippet 58, Robin Becker


"""
Packages: operating_systems.generic
"""

"""
>> How do I normalize a pathname in Python?  
>> For example, I have "../tools" and I want the full
>> pathname, e.g.  "c:/this/that/tools". 
>>  
>> os.normpath doesn't do exactly this. Is there a
>> way to do it in Python?
"""

import os

def _normjoin(a,b):
    return os.path.normpath(os.path.join(a,b))

def abspath(path):
    if os.name=='nt' or os.name=='dos':
        if len(path)>0 and path[0]=='.':
            return _normjoin(os.getcwd(),path)
        elif len(path)>1 and path[1]==':':
            if len(path)>2 and (path[2]=='\\' or path[2]=='/'):
                return path
            else:
                cwd=os.getcwd()
                os.chdir(path[0:2])
                path = _normjoin(os.getcwd(),path[2:])
                os.chdir(cwd)
                return path
        elif len(path)>0 and (path[0]=='\\' or path[0]=='/'):
            return path
        else:
            return _normjoin(os.getcwd(),path)
    elif os.name=='unix':
        if len(path)>0 and path[0]=='/': return path
        else: return _normjoin(os.getcwd(),path)
    elif os.name=='mac': raise NotImplementedError
    else: raise NotImplementedError