DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan Now×
Skip to content
World desk3 min

How to Create a CSV File in Python

Use Python’s built-in csv module to write rows or dictionary records to a CSV file, add a header, and handle newlines, encoding, and quoting correctly.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use Python’s built-in csv module to create a CSV file: open the file with newline="", then write rows with csv.writer or dictionary records with csv.DictWriter. The module is part of Python’s standard library, so ordinary CSV writing does not require an extra package.

Write rows from lists or other sequences

Use csv.writer when each record is an ordered sequence, such as a list or tuple. Include the header as the first row if the file should have column names:

import csv

rows = [
    ["name", "age", "city"],
    ["Ada", 36, "London"],
    ["Grace", 85, "New York"],
]

with open("people.csv", "w", newline="", encoding="utf-8") as file:
    writer = csv.writer(file)
    writer.writerows(rows)

writerows() writes an iterable of rows; use writer.writerow(row) when writing just one row. The "w" mode creates the file or truncates its existing contents. The CSV writer converts non-string values to text; None becomes an empty field, so that conversion cannot be reversed reliably just from the CSV.

Write dictionary records and add a header

For records represented as dictionaries, use csv.DictWriter. Its fieldnames argument sets the column order, and writeheader() writes those names as the first row:

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import csv

fieldnames = ["name", "age", "city"]
rows = [
    {"name": "Ada", "age": 36, "city": "London"},
    {"name": "Grace", "age": 85, "city": "New York"},
]

with open("people.csv", "w", newline="", encoding="utf-8") as file:
    writer = csv.DictWriter(file, fieldnames=fieldnames)
    writer.writeheader()
    writer.writerows(rows)

By default, a record containing a key that is not in fieldnames raises ValueError. If extra keys should be discarded, pass extrasaction="ignore" to DictWriter.

Choose the writer that matches your data

Input data Use How column order is set Header
Lists, tuples, or other ordered row sequences csv.writer The order of values in each row Write a header row yourself if needed
Dictionaries with named fields csv.DictWriter The fieldnames list Call writeheader() if needed

Avoid blank lines and malformed fields

Open with newline=""

When a file object is passed to a CSV writer, open it with newline="". Without it, embedded newlines in quoted fields can be handled incorrectly, and systems using CRLF line endings can produce extra carriage returns.

Let the writer quote values

The default CSV dialect uses commas and quotes fields when needed, including values containing commas, quote characters, or line breaks. Do not build rows by joining values with commas: a value that contains a comma or newline would make the output ambiguous. Use the writer so it can apply the quoting rules.

Set encoding for the receiving program

The examples specify encoding="utf-8", a practical explicit choice for many workflows. If the application receiving the file requires another encoding, use that encoding in open(); there is no single encoding that is correct for every recipient.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Match the CSV format expected by another application

CSV is not one perfectly uniform format. The default dialect is comma-delimited with standard quoting, but programs may expect different separators, quote characters, quoting behavior, line endings, or encodings. Configure options such as delimiter, quotechar, and quoting, or select a named dialect, when the target program requires it. Check that program’s import requirements rather than assuming one setting works everywhere.

Append rows without duplicating the header

Use file mode "a" to append instead of replacing a file. In an append workflow, decide whether the destination already has a header: writing it every time adds duplicate header rows. The CSV writer does not determine whether a header is already present, so manage that check as part of the surrounding program.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Remember that CSV stores text, not Python types

CSV output does not preserve Python types automatically. Values are represented as text, and ordinary CSV reading returns strings unless specific quoting behavior is selected. If a downstream program needs numbers, dates, or other typed values, define and document how those values should be converted when reading the file.

The Python Software Foundation describes the module as implementing classes to “read and write tabular data in CSV format.” See the Python 3.14.8 csv documentation for the writer options and dialect details.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.