Create the ShortCut of any File in Windows using Python

Hello Learners, today we are going to learn how can we create a shortcut of any file using Python. Creating shortcuts with Python is very easy and you just need to take a few steps and there you go!

So, without wasting any time, let’s jump into the code along with the explanation. Look at my desktop right now, you can see all the shortcuts.

shortcut bef

Let’s write a Python code to make a new shortcut.

import os, winshell, win32com.client, Pythoncom

desktop = winshell.desktop()
#desktop = r"path to where you wanna put your .lnk file"

path = os.path.join(desktop, 'File Shortcut Demo.lnk')
target = r"C:\Users\lenovo\Documents\sample2.txt" 
icon = r"C:\Users\lenovo\Documents\sample2.txt"

shell = win32com.client.Dispatch("WScript.Shell")
shortcut = shell.CreateShortCut(path)
shortcut.Targetpath = target
shortcut.IconLocation = icon
shortcut.save()

NOTE: If you want to create the shortcut on desktop you may need to install the Winchell module. It provides you the desktop method which returns the file system path of your desktop. But you can do it manually also by giving the path of your desktop to a variable.

EXPLANATION

  • os.path’s join method – it takes 2 parameters. The first parameter is the path of the folder where you want to create your shortcut and the Second parameter is the name of the shortcut.
  • target – the path of that file whose shortcut you want to create is stored in this variable.
  • icon – used to create the icon for the shortcut.
  • CreateShortCut method – creates the shortcut in the required folder whose path is given by you in the argument.
  • IconLocation method – extracts the icon for the shortcut directly from the executable file.
  • Dispatch method() – It is used for early binding purposes.

Note: The shortcut name must contain .lnk extension, as it is used to create the shortcuts to other files.

So, as you can see now, the shortcut of your file has been created when you have executed the code.

shortcut af

You can try it on your own and see how it works.

So, that’s all for now about how to create a shortcut of any file using Python.

Leave a Reply

Your email address will not be published. Required fields are marked *