To convert string to CSV in Python, write the text to a file opened with newline="" when it’s already comma-separated, or parse it into rows with csv.reader(io.StringIO(text)) and save those rows with csv.writer:
rows = list(csv.reader(io.StringIO(text)))
csv.writer(open("out.csv", "w", newline="")).writerows(rows)
I ran each script below on Python 3.12.5 and pandas 3.0.6, feeding it small US sales and order samples you can copy.
In this tutorial, we’ll convert string to CSV in Python five ways: saving CSV text as-is, parsing quoted fields, cleaning other delimiters, turning a JSON string into rows, and using pandas. Then we’ll go the other way.
Write a CSV-formatted string straight to a .csv file
If your string already looks like CSV (a header line, then one row per line), you don’t need to parse anything. Just write it:
sales = """date,city,amount_usd
2026-03-02,Austin,1250.00
2026-03-02,Denver,980.50
2026-03-03,Boston,1430.25
"""
with open("sales.csv", "w", newline="", encoding="utf-8") as f:
f.write(sales)
with open("sales.csv", encoding="utf-8") as f:
print(f.read())
Output:
date,city,amount_usd
2026-03-02,Austin,1250.00
2026-03-02,Denver,980.50
2026-03-03,Boston,1430.25
The newline="" argument stops Windows from adding blank lines between rows. If you’re new to file modes, my guide to Python with open explains them.
Parse a CSV string into rows with csv.reader and StringIO
Splitting on commas breaks as soon as a field contains one, like "Austin, TX". io.StringIO makes the string behave like a file, so csv.reader handles the quotes for you:
import csv
import io
text = 'name,city,total\nEmily Carter,"Austin, TX",1250.00\nJames Lee,"Denver, CO",980.50\n'
rows = list(csv.reader(io.StringIO(text)))
print(rows[1]) # the quoted comma stays inside one field
print("naive split:", text.splitlines()[1].split(","))
with open("customers.csv", "w", newline="", encoding="utf-8") as f:
csv.writer(f).writerows(rows)
print("rows written:", len(rows))
Output:
['Emily Carter', 'Austin, TX', '1250.00']
naive split: ['Emily Carter', '"Austin', ' TX"', '1250.00']
rows written: 3

Austin, TX together, while a plain split(",") cuts it into two fields.When you only need a Python list and no file, see converting a comma-separated string to a list.
How do you convert a string with other delimiters to CSV?
Exported text often uses pipes, semicolons or tabs. Split it into rows and fields first, strip the spaces, then let csv.writer add the commas:
import csv
raw = "SKU-101 | Desk Lamp | 34.99; SKU-102 | Office Chair | 189.00; SKU-103 | Monitor Arm | 59.95"
rows = [[part.strip() for part in item.split("|")] for item in raw.split(";")]
with open("products.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerow(["sku", "product", "price_usd"])
writer.writerows(rows)
print(open("products.csv", encoding="utf-8").read())
Output:
sku,product,price_usd
SKU-101,Desk Lamp,34.99
SKU-102,Office Chair,189.00
SKU-103,Monitor Arm,59.95

Splitting tricks for messier text are covered in splitting a string by comma in Python.
Convert a JSON string to a CSV file
APIs usually hand you JSON text. json.loads() turns it into a list of dictionaries, and csv.DictWriter writes the keys as the header:
import csv
import json
payload = '[{"order": 5001, "state": "TX", "total": 89.99}, {"order": 5002, "state": "NY", "total": 145.50}]'
orders = json.loads(payload)
with open("orders.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=orders[0].keys())
writer.writeheader()
writer.writerows({**o, "total": f"{o['total']:.2f}"} for o in orders) # keep the cents
print(open("orders.csv", encoding="utf-8").read())
Output:
order,state,total
5001,TX,89.99
5002,NY,145.50

JSON numbers load as floats, so 145.50 would be written as 145.5; the f-string puts the cents back.
For nested JSON or dictionaries in general, writing a Python dictionary to CSV goes further.
Convert a string to CSV with pandas read_csv
If you’ll analyze the data anyway, pandas reads a string through StringIO too. The sep argument handles any delimiter:
import io
import pandas as pd
text = "date;city;amount_usd\n2026-04-01;Seattle;720.40\n2026-04-01;Miami;1105.00\n"
df = pd.read_csv(io.StringIO(text), sep=";")
print(df)
print("total:", df["amount_usd"].sum())
df.to_csv("april_sales.csv", index=False, float_format="%.2f")
print(open("april_sales.csv", encoding="utf-8").read())
Output:
date city amount_usd
0 2026-04-01 Seattle 720.4
1 2026-04-01 Miami 1105.0
total: 1825.4
date,city,amount_usd
2026-04-01,Seattle,720.40
2026-04-01,Miami,1105.00

index=False keeps the row numbers out, and float_format="%.2f" stops 720.40 from turning into 720.4. The other pandas to_csv options are covered separately.
Turn rows back into a CSV string
Sometimes you need the reverse: a CSV string for an email body or an HTTP response, with no file at all. Write to a StringIO buffer and call getvalue():
import csv
import io
rows = [["city", "state", "temp_f"], ["Phoenix", "AZ", 104], ["Portland, Maine", "ME", 71]]
buffer = io.StringIO()
csv.writer(buffer, lineterminator="\n").writerows(rows)
csv_text = buffer.getvalue()
print(csv_text)
print(repr(csv_text.splitlines()[2]))
Output:
city,state,temp_f
Phoenix,AZ,104
"Portland, Maine",ME,71
'"Portland, Maine",ME,71'
Notice the writer quoted Portland, Maine automatically. For lists specifically, see writing a list to CSV in Python.
String to CSV methods compared
| Your string | Use | Handles quoted commas |
|---|---|---|
| Already CSV text | f.write(text) | Yes (kept as-is) |
| CSV text you need as rows | csv.reader(io.StringIO(text)) | Yes |
| Pipes, semicolons, tabs | split() + csv.writer | Yes, on write |
| JSON text | json.loads() + DictWriter | Yes |
| Data to analyze | pd.read_csv(io.StringIO(text)) | Yes |
Here are a few more CSV guides to try next:
- Create a CSV file in Python
- Read a CSV file with pandas
- Read large CSV files in Python
- Check if a string is comma-separated in Python
Frequently asked questions
How do I convert a string to CSV in Python?
Parse it with csv.reader(io.StringIO(text)) and save the rows with csv.writer, or write CSV-formatted text straight to a file.
Why does my CSV file have blank lines between rows?
Open the file with newline="". Without it, Windows adds an extra line break after each row.
How do I keep commas inside a field?
Let the csv module write the rows. It wraps fields like Austin, TX in double quotes.
Can I convert a string to CSV without creating a file?
Yes. Write rows to an io.StringIO buffer and read the text with getvalue().
How do I convert a JSON string to CSV?
Load it with json.loads(), then write the list of dictionaries with csv.DictWriter.
Where is the csv module documented?
See the csv module in the Python docs.

Bijay Kumar is a 13-time Microsoft MVP with more than 18 years in software development, and the founder of Python Guides and TSinfo Technologies. He started out building .NET and SharePoint solutions at HP, TCS and KPIT before moving into Python, machine learning and AI, and he also builds web apps with TypeScript and React. He writes the tutorials here himself, and every example is run before publishing so you see the real output. More about Bijay · Microsoft MVP profile · LinkedIn