How to copy the path of a selected file in Window Explorer?

Asked

Viewed 651 times

4

How to copy the full path containing the file name to the Clipboard using the "shortcut" CTRL-C? For example: Inside windows explorer select a file (teste.py) using the CTRL-C and then the CTRL-V in a text editor. I try the final result: c:\temp\teste.py

I’m initially thinking of using the widget Function Windows Explorer subprocess.Popen

import subprocess
subprocess.Popen(r'explorer /select,"c:\temp\"')

Once captured the file path I can copy it on Clipboard using a similar subroutine below:

from Tkinter import Tk
mypath = "c:/temp/teste.py"
r = Tk()
r.withdraw()
r.clipboard_clear()
r.clipboard_append(mypath)
r.destroy()

1 answer

1

You can use the module win32clipboard of Pywin32 (Most likely you already have it installed). The Getclipboarddata() function (which is usually used for text) accepts a format specification parameter of what is on the Clipboard, and in this case, you can pass the 15 value constant (CF_HDROP) used to move / copy files by CTR + C and CTR + V by Windows. I designed a brief get_path_of_file_on_clipboard function to illustrate:

from win32clipboard import OpenClipboard, GetClipboardData, CloseClipboard

def get_path_of_file_on_clipboard():
    CF_HDROP = 15
    OpenClipboard()
    data = "No file was selected."
    try:
        data = GetClipboardData(CF_HDROP)
    except TypeError:
        print("ERROR: You must copy a FILE to the clipboard.")
    finally:
        CloseClipboard()
    return data

print(get_path_of_file_on_clipboard())

This function returns a string with the absolute path to the file that was passed to the Clipboard (With CTR + C). Once you have obtained this path, just adapt to your application with Tkinter (Just capture the CTR + V event and insert that string where you want).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.