Accessing files in a directory which is a shortcut link (Windows)

Tim Golden mail at timgolden.me.uk
Sat May 2 12:35:35 EDT 2009


jorma kala wrote:
> Hi,
> I'd like to process files in a directory which is in fact a short cut link
> to another directory (under windows XP).
> If the path to the directory is for instance called c:\test. I have tried
> both following code snipets for printing all names of files in the
> directory:
> 
> ++ snippet 1++
> 
>      for filename in glob.glob( os.path.join(r'c:\test', '*') ):
>          print filename
> 
> ++ snippet 2++
> 
>      for filename in glob.glob( os.path.join(r'c:\test.lnk', '*') ):
>          print filename


Windows shortcuts are Shell (ie GUI Desktop) objects rather
than filesystem objects. The filesystem doesn't treat them
specially; just returns the .lnk file (or whatever it's
called). You need to invoke the Shell functionality specifically.

<code>
import os, sys
import glob
import pythoncom
from win32com.shell import shell, shellcon

def shortcut_target (filename):
  shell_link = pythoncom.CoCreateInstance (
    shell.CLSID_ShellLink, 
    None,
    pythoncom.CLSCTX_INPROC_SERVER, 
    shell.IID_IShellLink
  )
  ipersist = shell_link.QueryInterface (pythoncom.IID_IPersistFile)
  ipersist.Load (filename)
  name, _ = shell_link.GetPath (1)
  return name

def shell_glob (pattern):
  for filename in glob.glob (pattern):
    if filename.endswith (".lnk"):
      yield "%s => %s" % (filename, shortcut_target (filename))
    else:
      yield filename

for filename in shell_glob ("c:/temp/*"):
  print filename

</code>

TJG



More information about the Python-list mailing list