Reputation: 613
I used os.listdir(path)
to get the folder under specific path and found there is a shorcut inside.
How to get the real path of shortcut?
Input:
os.listdir('/tmp/logs')
Output:
Linux:
['12-31-2020_16-59-01-391', 'latest']
Windows:
['12-31-2020_16-59-01-391', 'latest.lnk']
Update:
A shortcut is added via the following picture so the real path of shortcut should be another path rather than /tmp/logs/latest.lnk
, something like C:\Users\username\Downloads\Temp\logs
.
Upvotes: 1
Views: 2822
Reputation: 31644
For linux, we can just use os.path.realpath
to get the target of symbol link.
But for windows, looks windows shortcut different with linux symbol link, you have to make workaround using pywin32
, utilize shell.CreateShortCut(item).Targetpath
.
A minimal example as next.
test.py:
import platform
import os
system = platform.system()
if system == "Linux":
print([os.path.realpath(item) for item in os.listdir('.')])
elif system == "Windows":
import win32com.client
shell = win32com.client.Dispatch("WScript.Shell")
print([shell.CreateShortCut(item).Targetpath if item.endswith("lnk") else item for item in os.listdir('.')])
else:
print('Unknown os.')
Upvotes: 3