← Back to Pandas Course | Chapter 11: File I/O | Lesson 7 of 7

String IO

StringIO lets you treat a string like a file, which is perfect for demos, tests and API responses.

In this page:

  1. String IO
Syntax
python
from io import StringIO
df = pd.read_csv(StringIO(text))

String IO

io.StringIO wraps text in a file-like object that Pandas can read from or write to. It avoids touching the disk. Use to_csv with no path to get a string, or pass a StringIO buffer to capture output.

Note: Call buf.seek(0) before re-reading a buffer you just wrote.

Example: String IO

python
import io
import pandas as pd

df = pd.DataFrame({"a": [1, 2], "b": ["x", "y"]})
buf = io.StringIO()
df.to_csv(buf, index=False)
buf.seek(0)
print(buf.read())
buf.seek(0)
print(pd.read_csv(buf).equals(df))

# Output:
# a,b
# 1,x
# 2,y
#
# True
Related Topics
Common Mistakes
  1. Forgetting seek(0) after writing
  2. Passing a plain string to newer read_json and read_html
  3. Reusing an exhausted buffer
Chapter Summary
  • StringIO makes strings file-like
  • No disk needed
  • seek(0) rewinds
  • Great for tests and demos
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.