Reputation: 147
When you try to open a shortcut file (.lnk) that no longer works, Windows lets you know with a prompt that says: "This shortcut has been changed or moved, so this shortcut will no longer work properly." Is there a python code I can use to detect whether such a shortcut no longer works?
When I run the following code to retrieve the target path of a shortcut that no longer works, I don't get any type of error. The code still prints the path to the target file that doesn't exist anymore:
import win32com.client
shell = win32com.client.Dispatch('WScript.Shell')
shortcut = shell.CreateShortcut(shortcutpath_cur)
target = shortcut_cur.Targetpath
print(target)
Sometimes a shortcut no longer works even if the document it points to still exists. In that case, I couldn't use os.path.exists()
or os.path.isfile()
because they would return True
.
Upvotes: 2
Views: 1367
Reputation: 381
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.
Upvotes: 3