You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python实现将文件复制到剪贴板的功能

Python实现文件复制到剪贴板

日常操作里我们可以用Ctrl + C复制文件到剪贴板,以下是不同操作系统下的Python实现代码:

Windows系统

通过调用Windows API直接操作剪贴板,无需额外安装依赖:

import ctypes
from ctypes import wintypes

path = r"C:\你的文件路径\test.txt"  # 替换为实际文件路径

def copy_file_to_clipboard() -> None:
    user32 = ctypes.WinDLL('user32', use_last_error=True)
    kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)
    CF_HDROP = 15

    class DROPFILES(ctypes.Structure):
        _fields_ = [("pFiles", wintypes.DWORD),
                    ("pt", wintypes.POINT),
                    ("fNC", wintypes.BOOL),
                    ("fWide", wintypes.BOOL)]

    if not user32.OpenClipboard(None):
        raise ctypes.WinError(ctypes.get_last_error())
    
    try:
        user32.EmptyClipboard()
        file_path = path.encode('utf-16le') + b'\x00\x00'
        drop_files_size = ctypes.sizeof(DROPFILES)
        h_global = kernel32.GlobalAlloc(0x40, drop_files_size + len(file_path))
        
        if not h_global:
            raise ctypes.WinError(ctypes.get_last_error())
        
        try:
            lp_global = kernel32.GlobalLock(h_global)
            if not lp_global:
                raise ctypes.WinError(ctypes.get_last_error())
            
            drop_files = DROPFILES()
            drop_files.pFiles = drop_files_size
            drop_files.fWide = True
            
            ctypes.memmove(lp_global, ctypes.byref(drop_files), drop_files_size)
            ctypes.memmove(ctypes.c_void_p(lp_global + drop_files_size), file_path, len(file_path))
            
            kernel32.GlobalUnlock(h_global)
            
            if not user32.SetClipboardData(CF_HDROP, h_global):
                raise ctypes.WinError(ctypes.get_last_error())
        finally:
            if not user32.IsClipboardFormatAvailable(CF_HDROP):
                kernel32.GlobalFree(h_global)
    finally:
        user32.CloseClipboard()

macOS系统

需要先安装pyobjc依赖(执行pip install pyobjc),通过AppKit操作剪贴板:

from AppKit import NSPasteboard, NSURL

path = "/Users/你的用户名/test.txt"  # 替换为实际文件路径

def copy_file_to_clipboard() -> None:
    pb = NSPasteboard.generalPasteboard()
    pb.clearContents()
    file_url = NSURL.fileURLWithPath_(path)
    pb.writeObjects_([file_url])

Linux系统

需要先安装xclip工具(例如Debian/Ubuntu下执行sudo apt install xclip),通过subprocess调用:

import subprocess

path = "/home/你的用户名/test.txt"  # 替换为实际文件路径

def copy_file_to_clipboard() -> None:
    subprocess.run(
        ["xclip", "-selection", "clipboard", "-t", "text/uri-list", "-i"],
        input=f"file://{path}".encode('utf-8'),
        check=True
    )

内容的提问来源于stack exchange,提问作者Ritwik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 18:55:26