问题
Following snippet shows how to extract the target of a shortcut in Windows:
import win32com.client
shell = win32com.client.Dispatch("WScript.Shell")
fp = r'C:\very_long_path\to\a\link\file\shortcut.lnk'
shortcut = shell.CreateShortCut(fp)
#targetPath = "\\\\?\\"+shortcut.Targetpath # Does not help
targetPath = shortcut.Targetpath
The code above fails if the lnk file is on a too long path. How can I get the shortcut's target path in this case?
回答1:
I believe the limitations you are facing are within the win32com.client.Dispatch("WScript.Shell")
this is why you are facing the 260 character limitation and the prefixing with \\?\
is not solving your problem.
You will have to work around it by
- copying folder to a shorter path (the copying can be done with
\\?\
prefix to avoid limitation of path length) - then create the shortcut (without
\\?\
prefix), but with the longer path target. - and copy all back (again with
\\?\
prefix).
Alternatively you can consider using a Symbolic Link in stead of a Shortcut (Windows Vista and higher) which can be created with os.symlink()
and this will work with \\?\
prefix for long path names. This is what I personally have done multiple times, as it is just simpler to implement. But you will have to ask the question if this "shortcut" or "symlink" is really needed, as once you have a "symlink" you do need to delete both source as symlink upon delete, else your file will remain.
Lastly you can do this the hard way: recreate code to create a shortcut file in the correct format. Here is some Microsoft Documentation, a search online will reveal multiple links with useful information.
Although I do not have experience with this, there seems to be a module which claims it can natively create .lnk files
来源:https://stackoverflow.com/questions/48443197/windows-path-too-long