Modify Windows shortcuts using Python

前端 未结 5 828
被撕碎了的回忆
被撕碎了的回忆 2020-12-09 21:46

How do you change a Windows shortcut using Python?

e.g. from:

H:\\My Music\\some_file.mp3

to:

D:\\Users\\Myself\\My         


        
5条回答
  •  情书的邮戳
    2020-12-09 22:08

    Jonathan's solution works perfectly. This is the useful function I produced implementing this. Simply pass in the name of the shortcut file (for example "Mozilla Firefox.lnk", it is unnecessary to specify the entire filepath), and the new shortcut destination, and it will be modified.

    import os, sys
    import pythoncom
    from win32com.shell import shell, shellcon
    
    def short_target(filename,dest):
        shortcut = pythoncom.CoCreateInstance (
            shell.CLSID_ShellLink,
            None,
            pythoncom.CLSCTX_INPROC_SERVER,
            shell.IID_IShellLink
        )
        desktop_path = shell.SHGetFolderPath (0, shellcon.CSIDL_DESKTOP, 0, 0)
        shortcut_path = os.path.join (desktop_path, filename)
        persist_file = shortcut.QueryInterface (pythoncom.IID_IPersistFile)
        persist_file.Load (shortcut_path)
        shortcut.SetPath(dest)
        mydocs_path = shell.SHGetFolderPath (0, shellcon.CSIDL_PERSONAL, 0, 0)
        shortcut.SetWorkingDirectory (mydocs_path)
        persist_file.Save (shortcut_path, 0)
    

    The only dependency is the pywin32 library. Also note that one is able to specify options and arguments in their shortcut destination. To implement, just call:

    short_target("shortcut test.lnk",'C:\\')   #note that the file path must use double backslashes rather than single ones. This is because backslashes are used for special characters in python (\n=enter, etc) so a string must contain two backslashes for it to be registered as one backslash character.
    

    This example will set the destination of a shortcut on your desktop called "shortcut test" to a shortcut that opens up the file manager in the root directory of the hard drive (C:).

提交回复
热议问题