Pandas read_clipboard(): Read Pasted Tables and Desktop Clipboard Text

Use read_clipboard() with the local operating-system clipboard. Practise the same table parsing and text formatting in Colab using the portable examples below.

Desktop clipboard access and Colab pasted-text practice are different workflows. The notebook keeps desktop calls disabled for Run All.
read_clipboard(): Read the clipboad data and create DataFrame #B12
Python Pandas reading data from Clipboard and create DataFrame by using read_clipboard()

Read pasted table text in Colab 🔝

The synthetic Ravi, Raju and Alex table preserves the original marks. Paste tabular text into a string and parse it with read_csv(StringIO(...)). This portable route uses no operating-system clipboard. Use tabs for spreadsheet cells so spaces inside names stay intact. See read_csv().
import pandas as pd
import tempfile
import sqlite3
from pathlib import Path
from io import StringIO
pasted = 'NAME\tID\tMATH\tENGLISH\nRavi\t1\t30\t20\nRaju\t2\t40\t30\nAlex\t3\t50\t40\n'
df = pd.read_csv(StringIO(pasted), sep="	")
print(df)
assert df["NAME"].tolist() == ["Ravi", "Raju", "Alex"]

Expected output

   NAME  ID  MATH  ENGLISH
0  Ravi   1    30       20
1  Raju   2    40       30
2  Alex   3    50       40

Read the desktop clipboard 🔝

On local Python, copy a table from a spreadsheet or the DataFrame example, then set run_desktop=True below. The expected table depends on your copied content. The default separator is a whitespace regex, not a single space. For spreadsheet text, an explicit tab separator is usually clearer. Desktop access is disabled for portable Run All.
run_desktop = False  # Set True only in local Python after copying a table.
if run_desktop:
    local_table = pd.read_clipboard(sep="	")
    print(local_table)
else:
    print("Desktop clipboard read is disabled; use the pasted-text examples.")

Expected output

Desktop clipboard read is disabled; use the pasted-text examples.

Parse whitespace and keep names with spaces 🔝

Default read_clipboard() uses one-or-more whitespace characters. This is useful for simple console tables, but may split multiword fields. The first example has single-word names; the second uses tabs to retain John Deo.
console = 'NAME ID MATH ENGLISH\nRavi 1 30 20\nRaju 2 40 30\nAlex 3 50 40\n'
simple = pd.read_csv(StringIO(console), sep=r"\s+")
print(simple)
names = pd.read_csv(StringIO('id\tname\n1\tJohn Deo\n'), sep="	")
assert names.loc[0, "name"] == "John Deo"
print(names)

Expected output

   NAME  ID  MATH  ENGLISH
0  Ravi   1    30       20
1  Raju   2    40       30
2  Alex   3    50       40
   id      name
0   1  John Deo

Choose an em-dash separator and Python engine 🔝

Retain the original function-description delimiter example with embedded practice text. Inspect copied text from the PHP string manual before parsing. The Unicode em dash and regex separators may require engine="python". This sample describes functions for practice rather than fetching the live manual.
functions_text = 'function—description\nstrlen—Return string length\ntrim—Remove surrounding whitespace\n'
functions = pd.read_csv(StringIO(functions_text), sep="—", engine="python")
print(functions)
assert functions.columns.tolist() == ["function", "description"]

Expected output

  function                    description
0   strlen           Return string length
1     trim  Remove surrounding whitespace

Keep identifiers and validate missing values 🔝

read_clipboard() accepts read_csv options such as dtype, header and na_values. Choose identifiers as text before parsing; add headers explicitly when the copied region has none.
records = '001\t75\n002\tpending\n'
typed = pd.read_csv(StringIO(records), sep="	", header=None,
    names=["id", "mark"], dtype={"id": "string"}, na_values=["pending"])
print(typed)
assert typed["id"].tolist() == ["001", "002"]
assert typed["mark"].isna().sum() == 1

Expected output

    id  mark
0  001  75.0
1  002   NaN

Save imported data as CSV and Excel 🔝

Preserve the original file-export workflow using portable paths. index=False avoids exporting disposable row numbers. openpyxl is needed for the Excel example. See to_csv() and to_excel().
with tempfile.TemporaryDirectory(dir=Path.cwd()) as folder:
    csv_file = Path(folder) / "my_clipboard.csv"
    excel_file = Path(folder) / "my_clipboard.xlsx"
    df.to_csv(csv_file, index=False)
    df.to_excel(excel_file, index=False, engine="openpyxl")
    pd.testing.assert_frame_equal(pd.read_csv(csv_file), df)
    pd.testing.assert_frame_equal(pd.read_excel(excel_file, engine="openpyxl"), df)
    print("CSV and Excel round trips passed")

Expected output

CSV and Excel round trips passed

Create an HTML table from imported text 🔝

Write an escaped HTML table using to_html(). escape=True keeps text values from becoming markup. The output below is the actual generated table source, preserving the original HTML teaching example.
HTML table generated from imported clipboard data
table_html = df.to_html(index=False, escape=True)
print(table_html)
with tempfile.TemporaryDirectory(dir=Path.cwd()) as folder:
    target = Path(folder) / "my_html.html"
    target.write_text(table_html, encoding="utf-8")
    assert target.read_text(encoding="utf-8") == table_html

Expected output

<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th>NAME</th>
      <th>ID</th>
      <th>MATH</th>
      <th>ENGLISH</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Ravi</td>
      <td>1</td>
      <td>30</td>
      <td>20</td>
    </tr>
    <tr>
      <td>Raju</td>
      <td>2</td>
      <td>40</td>
      <td>30</td>
    </tr>
    <tr>
      <td>Alex</td>
      <td>3</td>
      <td>50</td>
      <td>40</td>
    </tr>
  </tbody>
</table>

Common clipboard import pitfalls 🔝

Copy a rectangular table with a consistent delimiter. Avoid merged cells, extra titles and footnotes. sep and engine are parsing choices; changing engine does not repair a missing clipboard service. A local/headless backend may report PyperclipException when unavailable. Colab runs remotely and cannot read your Windows clipboard; paste text or upload a CSV/Excel file instead. Clipboard data is transient, so save useful imports. Verify row counts, headers, dtypes and missing values before analysis. A headerless table needs header=None and names. Regex separators can interact poorly with quoted delimiters; prefer a standard delimiter where possible.

Exercise: parse functions and export them 🔝

Parse the em-dash function text above, then write an Excel file without an index. Verify the two function names. This retains the original PHP-function worksheet exercise.

Exercise solution 🔝

Use the Python parser for the supplied em-dash text, export and read the worksheet back.
answer = pd.read_csv(StringIO(functions_text), sep="—", engine="python")
with tempfile.TemporaryDirectory(dir=Path.cwd()) as folder:
    target = Path(folder) / "php_functions.xlsx"
    answer.to_excel(target, index=False, engine="openpyxl")
    checked = pd.read_excel(target, engine="openpyxl")
    assert checked["function"].tolist() == ["strlen", "trim"]
    print(checked)

Expected output

  function                    description
0   strlen           Return string length
1     trim  Remove surrounding whitespace

Practice in Google Colab 🔝

Open in Google Colab View on GitHub

Run examples in order. Portable examples create their own files; desktop clipboard calls are disabled by default. Save a copy to keep edits.

Reference: Pandas read_clipboard documentation.




Subscribe to our YouTube Channel here



plus2net.com







Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
Python Tkinter Video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer