When you do Copy
(CTRL+C) on a file, then in some programs (example: it works in the Windows Explorer address bar, also with Everything indexing software), when doing Paste (CTRL+V), the filename or directory name is pasted like text, like this: "d:\test\hello.txt"
.
I tried this:
Run:
import win32clipboard
win32clipboard.OpenClipboard()
data = win32clipboard.GetClipboardData()
win32clipboard.CloseClipboard()
print data
But I get this error:
TypeError: Specified clipboard format is not available
Question: how to retrieve the filename of a file that has been "copied" (CTRL+C) in the Windows Explorer?
getName() method returns the last name of the pathname's name sequence, that means the name of the file or directory denoted by this abstract path name is returned.
The clipboard may contain more than one format. For example, when formatted text is copied from MS word, both the formatted text and the plain text will be in the clipboard, so that depending on the application into which you are pasting, the target application may take one or the other format, depending on what it supports.
From MSDN:
A window can place more than one clipboard object on the clipboard, each representing the same information in a different clipboard format. When placing information on the clipboard, the window should provide data in as many formats as possible. To find out how many formats are currently used on the clipboard, call the CountClipboardFormats function.
Because of that, win32clipboard.GetClipboardData
takes one argument: format
, which is by default win32clipboard.CF_TEXT
.
When you call it without arguments, it raises error saying TypeError: Specified clipboard format is not available
, because TEXT format is not in the clipboard.
You can, instead, ask for win32clipboard.CF_HDROP
format, which is "A tuple of Unicode filenames":
import win32clipboard
win32clipboard.OpenClipboard()
filenames = win32clipboard.GetClipboardData(win32clipboard.CF_HDROP)
win32clipboard.CloseClipboard()
for filename in filenames:
print(filename)
See also MSDN doc for standard clipboard formats
This worked for me:
import win32clipboard
win32clipboard.OpenClipboard()
filename_format = win32clipboard.RegisterClipboardFormat('FileName')
if win32clipboard.IsClipboardFormatAvailable(filename_format):
input_filename = win32clipboard.GetClipboardData(filename_format).decode("utf-8")
print(input_filename)
win32clipboard.CloseClipboard()
That prints the whole file path, if you want just the file name use:
os.path.basename(input_filename)
Try to use this argument >>> CF_UNICODETEXT like this win32clipboard.GetClipboardData(win32clipboard.CF_UNICODETEXT) It's work for me. Refer: https://learn.microsoft.com/en-us/windows/win32/dataxchg/standard-clipboard-formats
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With