I need to use python 3 to create a shortcut to go to some site. The file must have the extension ".url". How can I do this?
I found some code but it doesn't work for me
bmurl = card.url # some link
bmpath = path_to_card "link.url" # path to file
ws = win32com.client.Dispatch("wscript.shell")
scut = ws.CreateShortcut(bmpath)
scut.TargetPath = bmurl # in this place I got an error
scut.Save()
CodePudding user response:
To create a shortcut file with the ".url" extension in Python, you can use the win32com module to create a ShellLinkObject and set its TargetPath property to the URL that you want the shortcut to point to. Here is an example of how you could do this:
import win32com.client
bmurl = "https://www.example.com"
bmpath = "link.url"
# Create a ShellLinkObject.
scut = win32com.client.Dispatch("wscript.shell").CreateShortcut(bmpath)
# Set the TargetPath property of the shortcut to the URL.
scut.TargetPath = bmurl
# Save the shortcut.
scut.Save()
In the code above, I first import the win32com module, which provides access to the Windows Script Host Object Model. I then create a ShellLinkObject by calling the Dispatch method of the win32com.client module and passing it the string "wscript.shell", which specifies the type of object to create. I call the CreateShortcut method of the ShellLinkObject and pass it the path of the shortcut file (bmpath) to create the shortcut.
Next, I set the TargetPath property of the shortcut to the URL that I want the shortcut to point to (bmurl). Finally, I call the Save method of the ShellLinkObject to save the shortcut file.