Reading the Target of a .Lnk File in Python

Reading the target of a .lnk file in Python?

Create a shortcut using Python (via WSH)

import sys
import win32com.client

shell = win32com.client.Dispatch("WScript.Shell")
shortcut = shell.CreateShortCut("t:\\test.lnk")
shortcut.Targetpath = "t:\\ftemp"
shortcut.save()


Read the Target of a Shortcut using Python (via WSH)

import sys
import win32com.client

shell = win32com.client.Dispatch("WScript.Shell")
shortcut = shell.CreateShortCut("t:\\test.lnk")
print(shortcut.Targetpath)

How do I get the target of a web shortcut lnk file?

You need to create the web shortcut in a slightly different way. According to this TechNet forum posting, the filename must have an extension of .url rather than .lnk, and you must explicitly call the .Save() method of the object.

General approach to reading lnk files

There is not an official document from Microsoft describing lnk file format but there are some documents which have description of the format. Here is one of them: Shortcut File Format (.lnk)

As for the API you can use IShellLink Interface

Can python detect whether a shortcut file (.lnk) no longer works?

You could do this by attempting to check if the file path has an existing file. There is a solution here on SO that contains many ways to do this:
How do I check whether a file exists without exceptions?

If you check if the file exists at the path specified by the shortcut you can then detect whether the shortcut itself would work and do your own procedures for it.

Here is a quote from the link above that you could use to do this:

"If you're not planning to open the file immediately, you can use os.path.isfile

Return True if path is an existing regular file. This follows symbolic links, so both islink() and isfile() can be true for the same path.

import os.path
os.path.isfile(fname)

if you need to be sure it's a file."

If for some reason the file exists but your shortcut doesnt work, this wouldn't work. You could then use a try: to open the file and except: all the possible errors that may arise. Sometimes a shortcut won't work because of insufficient permissions or because the target is no longer valid.

If the file exists but it won't open via shortcut then it's a problem with the shortcut file itself, the target file, an operating system bug/glitch, or insufficient permissions.



Related Topics



Leave a reply



Submit