Welcome, guest | Sign In | My Account | Store | Cart

In Windows it is often useful to get the "Short Name" version (8.3) of a file or directory path. The Windows api does not provide a function that one can call for this.

Python, 21 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
def getShortPathName(filepath):
    "Converts the given path into 8.3 (DOS) form equivalent."
    import win32api, os
    if filepath[-1] == "\\":
        filepath = filepath[:-1]
    tokens = os.path.normpath(filepath).split("\\")
    if len(tokens) == 1:
        return filepath
    ShortPath = tokens[0]
    for token in tokens[1:]:
        PartPath = "\\".join([ShortPath, token])
        Found = win32api.FindFiles(PartPath)
        if Found == []:
            raise WindowsError, 'The system cannot find the path specified: "%s"' % (PartPath)
        else:
            if Found[0][9] == "":
                ShortToken = token
            else:
                ShortToken = Found[0][9]
            ShortPath = ShortPath + "\\" + ShortToken
    return ShortPath

It simply calls the windows FindFiles function for evey part of the path to get the short name version and returns the fully converted path. Note that the short path name to a file or directory is not static. It may change if there are other files or directories being added or removed adjacent to the ones being listed. For example, "C:\Progra~1" ("C:\Program Files") may become "C:Progra~2" if another folder is created that trumps it according to the naming rules. So, you can't save the short path name and expected it to be valid the next time you use it. You will have to call this function every time the short path to a file or directory is needed.

4 comments

Simon Brunning 17 years, 5 months ago  # | flag

win32api.GetShortPathName().

>>> import win32api
>>> win32api.GetShortPathName('D:/share/from_roadwarrior/simon/python/RandomizeScreenSaver/RandomizeScreenSaver.pyw')
'D:/share/FROM_R~1/simon/python/RANDOM~1/RANDOM~1.PYW'
Ruben Marquez (author) 17 years, 5 months ago  # | flag

Re:win32api.GetShortPathName(). Oops. I guess I was misinformed. I should have looked deeper in the docs. Thank you for clearing this up.

Sam Spade 17 years, 4 months ago  # | flag

Beware... Using the Windows API function only works if the file exists in the specified path.

Simon Brunning 17 years, 4 months ago  # | flag

This is just as it should be... Files that don't exist don't have short names. One might be able to put together a function that guesses what short name Windows would be likely to give a new file with a given long name, but it would be pretty unreliable, I reckon.