How to copy a file to the memory in Python on Windows
我使用Python开发了一个桌面应用程序,我需要使用户能够复制应用程序窗口(而不是Windows资源管理器)中显示的文件,以便他们可以将其粘贴到所需的位置。
就像Windows中的"右键单击并复制"或" ctrl + V"一样。
我只找到了一个python函数,用于将文件从使用dir的一个目录复制到
1 2 | shutil.copy(src, dst) Copy the file src to the file or directory dst. If dst is a directory, a file with the same basename as src is created (or overwritten) in the directory specified. Permission bits are copied. src and dst are path names given as strings. |
但是我想将其保存在内存中,所以当用户单击"粘贴"时,文件出现
我该如何实现?
您需要的剪贴板格式为
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | import ctypes from ctypes import wintypes import pythoncom import win32clipboard class DROPFILES(ctypes.Structure): _fields_ = (('pFiles', wintypes.DWORD), ('pt', wintypes.POINT), ('fNC', wintypes.BOOL), ('fWide', wintypes.BOOL)) def clip_files(file_list): offset = ctypes.sizeof(DROPFILES) length = sum(len(p) + 1 for p in file_list) + 1 size = offset + length * ctypes.sizeof(ctypes.c_wchar) buf = (ctypes.c_char * size)() df = DROPFILES.from_buffer(buf) df.pFiles, df.fWide = offset, True for path in file_list: array_t = ctypes.c_wchar * (len(path) + 1) path_buf = array_t.from_buffer(buf, offset) path_buf.value = path offset += ctypes.sizeof(path_buf) stg = pythoncom.STGMEDIUM() stg.set(pythoncom.TYMED_HGLOBAL, buf) win32clipboard.OpenClipboard() try: win32clipboard.SetClipboardData(win32clipboard.CF_HDROP, stg.data) finally: win32clipboard.CloseClipboard() if __name__ == '__main__': import os clip_files([os.path.abspath(__file__)]) |