Skip to content
Advertisement

Python get filepath

I’m trying to create a simple script to copy the filepath of a selected file (in windows explorer) to the clipboard in python. I’ve been looking at pyperclip and tkinter but I’m unsure how exactly to proceed.

The askopenfilename in tkinter seems promising, but I’d like to select the files outside python and then call the script through the windows context menu.


EDIT:

I want to create a script which can alter a local filepath to a network path when I copy it using the windows context menu (right click).

e.g. when right-clicking on my file C:UsersLocalUsertest.txt in windows explorer I want to add a dropdown option to copy the filepath, but change the directory to e.g. D:UsersLocalUsertest.txt.

I’m thinking of adding the context menu option by adding a new key in RegEdit and adding a shortcut to the python script in ComputerHKEY_CLASSES_ROOT*shell, but in order to do so, I need to be able to copy add the filepath to my clipboard first.

Advertisement

Answer

You are right, to add something in windows context menu, you will need to edit the windows registry editor.

To copy filelocation in clipboard, you can use pyperclip but this can be done using only tkinter :

from tkinter import Tk, filedialog

r = Tk()
r.withdraw()
filename = filedialog.askopenfilename()
#print(filename)
r.clipboard_clear()
r.clipboard_append(filename)
r.update() # now it stays on the clipboard after the window is closed
r.destroy()

What you can do is, when in file explorer, you right-click, then in the context menu, there will be an option (such as, “copy the file location of a file”) which you can add using registry editor. Then on clicking that option, another file dialog is opened, in which the location of whichever file you select is then copied to your clipboard.


EDIT: To only add a “Copy Path” option in the context menu:

Reference

In registry editor, for files, in HKEY_CLASSES_ROOT*shellCopy Pathcommand, and for folders, in HKEY_CLASSES_ROOTDirectoryshellCopy Pathcommand, add the following command by setting the value of (Default) to

cmd.exe /c (echo.|set /p=%1) | clip

That’s it, without python, using only the default command line interpreter, you can copy the full path of file/folders in windows.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement