How to get the target of a Windows shortcut file

Steve M sjmaster at gmail.com
Fri May 5 18:12:13 EDT 2006


Below is some code adapted from something I think was written by Mark
Hammond. Originally I needed to create a Windows shortcut (link), and
this code does the trick, requiring only the target filename and the
desired shortcut name.
Now, I find I need to open a shortcut and extract the target filename,
and I don't have a clue how that is achieved. To be clear, I mostly
don't understand the gory (Windows API) details of this code. So, can
anyone show how to open an existing shortcut file (given its name) and
discover the name of the file to which it is a shortcut?


import os
from win32com.shell import shell
import pythoncom

# Get the shell interface.
sh = pythoncom.CoCreateInstance(shell.CLSID_ShellLink, None, \
    pythoncom.CLSCTX_INPROC_SERVER, shell.IID_IShellLink)

# Get an IPersist interface
persist = sh.QueryInterface(pythoncom.IID_IPersistFile)

target_of_link = os.path.abspath('target.doc')
link_name = 'shortcut_to_target.doc.lnk'

sh.SetPath(target_of_link)
persist.Save(link_name, 1)




More information about the Python-list mailing list