String IO
StringIO lets you treat a string like a file, which is perfect for demos, tests and API responses.
In this page:
Syntax
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
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
- Forgetting seek(0) after writing
- Passing a plain string to newer read_json and read_html
- 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: