[Python] How to Read and Write Clipboard Data with Pandas (read_clipboard / to_clipboard)

If you want to import table data from Excel, spreadsheets, or websites into Python, saving it as a CSV file first can be time-consuming. By using Pandas’ read_clipboard and to_clipboard, you can instantly link data between DataFrames and external applications using just copy and paste operations.

This article explains how to input and output data via the clipboard.

目次

Notes on Execution Environment (For Linux Users)

While this feature works by default on Windows and macOS, Linux environments (including WSL) may require an external package to manipulate the clipboard. If you encounter an error, please install xsel or xclip using the following command.

# For Linux / WSL environments
sudo apt install xsel

Implementation Sample Code

The following code performs two operations:

  1. Write: Copies the created DataFrame to the clipboard (ready to be pasted into Excel, etc.).
  2. Read: Reads the data currently in the clipboard and creates a new DataFrame.

Note: This code is intended for execution in a local environment (your own PC). It will not work in cloud environments like Google Colab because access to the clipboard is restricted.

import pandas as pd

def clipboard_interaction_demo():
    """
    Function to demonstrate writing to and reading from the clipboard using Pandas
    """
    
    # === 1. Write DataFrame to Clipboard (to_clipboard) ===
    print("=== Writing to Clipboard ===")
    
    # Sample Data: Server Monthly Uptime Status
    server_stats = {
        "Server_Name": ["Alpha_01", "Beta_02", "Gamma_03", "Delta_04"],
        "Uptime_Hours": [720, 715, 698, 720],
        "Error_Count": [0, 2, 5, 0],
        "Status": ["Stable", "Warning", "Critical", "Stable"]
    }
    
    df_source = pd.DataFrame(server_stats)
    
    print("--- Source DataFrame ---")
    print(df_source)
    
    # Copy to clipboard
    # excel=True : Copy in Excel format (Default)
    # index=False : Do not include row numbers
    try:
        df_source.to_clipboard(index=False)
        print("\n>> Data copied to clipboard.")
        print(">> Try opening Excel or Notepad and 'Pasting' the data.\n")
    except Exception as e:
        print(f"\n[Error] Failed to access clipboard: {e}")
        return

    # === 2. Read Data from Clipboard (read_clipboard) ===
    print("=== Reading from Clipboard ===")
    print(">> Reading the data that was just copied...")
    
    # Get clipboard content as a DataFrame
    # If you run this after copying a table from the Web or a range in Excel, it will be loaded
    try:
        df_pasted = pd.read_clipboard()
        
        print("--- Loaded DataFrame ---")
        print(df_pasted)
        
        # Check data types
        print("\n--- Data Type Check ---")
        print(df_pasted.dtypes)
        
    except Exception as e:
        print(f"\n[Error] Failed to read: {e}")

if __name__ == "__main__":
    clipboard_interaction_demo()

Image of Execution Result

When you run the code, the following will be displayed in the console, and the data will be stored in the OS clipboard at the same time. If you open Excel and press Ctrl+V in this state, the data will be pasted in a clean table format.

=== Writing to Clipboard ===
--- Source DataFrame ---
  Server_Name  Uptime_Hours  Error_Count    Status
0    Alpha_01           720            0    Stable
1     Beta_02           715            2   Warning
2    Gamma_03           698            5  Critical
3    Delta_04           720            0    Stable

>> Data copied to clipboard.
>> Try opening Excel or Notepad and 'Pasting' the data.

=== Reading from Clipboard ===
>> Reading the data that was just copied...
--- Loaded DataFrame ---
  Server_Name  Uptime_Hours  Error_Count    Status
0    Alpha_01           720            0    Stable
1     Beta_02           715            2   Warning
2    Gamma_03           698            5  Critical
3    Delta_04           720            0    Stable

Explanation

Use Cases for read_clipboard

If executed without arguments, pd.read_clipboard() automatically parses the text in the clipboard. By default, it intelligently distinguishes between tab and space delimiters, but you can use the sep argument if you want to specify the delimiter explicitly.

  • Importing from Excel: You can convert data to a DataFrame simply by copying a cell range in Excel and running pd.read_clipboard().
  • Web Tables: It is also possible to select and copy a <table> tag table on a browser and load it directly.

Use Cases for to_clipboard

  • Quick Reports: This is convenient when you want to paste results aggregated in Python into Excel to create graphs or reports.
  • CSV-free Integration: This eliminates the need to generate and save CSV files for temporary data verification.

This feature serves as a very powerful shortcut that removes the “wall” between tools during the trial-and-error stage of data analysis.

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次