How to Convert a String to CSV in Python

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
Command Prompt output of Python csv.reader parsing a CSV string with StringIO, keeping Austin, TX in one field unlike str.split
csv.reader keeps 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
Command Prompt output of Python turning a pipe and semicolon delimited string into a products CSV file with csv.writer
Three products separated by semicolons become three CSV rows under a header line.

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
Command Prompt output of Python converting a JSON string of orders to a CSV file with json.loads and csv.DictWriter
The JSON keys order, state and total become the header row of orders.csv, and both totals keep two decimals.

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
Command Prompt output of pandas read_csv reading a semicolon string through StringIO and saving it with to_csv
pandas reads the semicolon text into a DataFrame, sums the USD amounts and saves a comma-separated file.

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 stringUseHandles quoted commas
Already CSV textf.write(text)Yes (kept as-is)
CSV text you need as rowscsv.reader(io.StringIO(text))Yes
Pipes, semicolons, tabssplit() + csv.writerYes, on write
JSON textjson.loads() + DictWriterYes
Data to analyzepd.read_csv(io.StringIO(text))Yes

Here are a few more CSV guides to try next:

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.