Modify Windows shortcuts using Python

Viewed 12948

How do you change a Windows shortcut using Python?

e.g. from:

H:\My Music\some_file.mp3

to:

D:\Users\Myself\My Music\some_file.mp3
5 Answers

The previous answer are perfectly valid however to really complete them I added the code for bulk editing because I suppose you might have a lots of link to edit.

use this if you want to edit many links at once:

import os, sys
import glob
import pythoncom
from win32com.shell import shell, shellcon

def shortcut_target (filename):
  link = pythoncom.CoCreateInstance (
    shell.CLSID_ShellLink,    
    None,
    pythoncom.CLSCTX_INPROC_SERVER,    
    shell.IID_IShellLink
  )
  persist_file = link.QueryInterface (pythoncom.IID_IPersistFile)
  persist_file.Load (filename)
  #
  # GetPath returns the name and a WIN32_FIND_DATA structure
  # which we're ignoring. The parameter indicates whether
  # shortname, UNC or the "raw path" are to be
  # returned. Bizarrely, the docs indicate that the 
  # flags can be combined.
  #
  name, _ = link.GetPath (shell.SLGP_UNCPRIORITY)

  target = name
  target = target.replace('H:\My Music', 'D:\Users\Myself\My Music')

  link.SetPath(target)
  persist_file.Save(filename, 0)

  return name

def shell_glob (pattern):
  for filename in glob.glob (pattern):
    if filename.endswith (".lnk"):
      print shortcut_target(filename)



desktop = "H:\My Music\"
for filename in shell_glob (os.path.join (desktop, "*")):
  print filename
Related