How to convert long Win95 paths to 8.3 dos paths?

Christian Tismer tismer at appliedbiometrics.com
Fri May 7 09:38:14 EDT 1999


Tim Peters wrote:
> 
> [Michael Scharf]
> > I am looking for a function, that can convert
> > long NT or Win95 names to 8.3 dos names
> > (the same name that 'dir /x' would show).
> > I could not find anything relevant in the
> > with dejanews nor on the python pages...
> 
> Heh.  Heh heh.  Here's an extract from
>     http://www.zdjournals.com/ddj/9608/ddj9681.htm
> 
>     You might expect to find [an MS API] function that will perform
>     the necessary conversions from a long filename to an alternate
>     filename and back. Surprisingly, the Windows 95 API doesn't supply
>     such a function.

Well, it has to be done step by step using FindFile.
Here a Python version.

ciao - chris

--- BEGIN shrtname.py ---
import win32api, string

def LongToShort(fname):
    pieces = string.split(string.replace(fname, "/", "\\"), "\\")
    if not pieces: return ""
    pre = pieces.pop(0)
    if not pre or pre[-1:]==":" : # abs path
        pre = pre + "\\"
        if not pieces: return ""
        first = pieces.pop(0)
    else:  # rel path
        parts = string.split(pre, ":", 1)
        if len(parts) > 1:
            pre = parts[0] + ":"
            first = parts[1]
        else:
            first = pre
            pre = ""
    try:
        oldpath = pre+first
        newpath = pre+_get_short(oldpath)
        for piece in pieces:
            oldpath = oldpath + "\\" + piece
            newpath = newpath + "\\" + _get_short(oldpath)
        return newpath
    except TypeError: return ""  # we got none for the short path
        
def _get_short(longpath):
    dir = win32api.FindFiles(longpath)
    if dir: 
        short = dir[0][-1]
        if not short:
            short = dir[0][-2] # was a true short one
        return short
            
---END shrtname.py ---

-- 
Christian Tismer             :^)   <mailto:tismer at appliedbiometrics.com>
Applied Biometrics GmbH      :     Have a break! Take a ride on Python's
Kaiserin-Augusta-Allee 101   :    *Starship* http://starship.python.net
10553 Berlin                 :     PGP key -> http://wwwkeys.pgp.net
PGP Fingerprint       E182 71C7 1A9D 66E9 9D15  D3CC D4D7 93E2 1FAE F6DF
     we're tired of banana software - shipped green, ripens at home




More information about the Python-list mailing list