Python
CSV
Data Export
Programming
File Handling

Create a .csv file with values from a Python list

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Creating a CSV file from a Python list is simple if you use the standard csv module and match the writer to the shape of your data. Most problems come from trying to build CSV text manually, which breaks quoting, delimiters, or newline handling. A good export routine keeps the structure explicit and lets the library handle the file format rules.

Start With the Shape of the List

Before writing anything, decide what kind of list you have:

  • a flat list of values
  • a list of rows
  • a list of dictionaries

Each shape maps to a slightly different API. Choosing the correct one keeps the code small and avoids unnecessary conversion steps.

Write a One-Column CSV From a Flat List

If your list contains plain values, write one row per item.

python
1import csv
2
3fruits = ["apple", "banana", "cherry"]
4
5with open("fruits.csv", "w", newline="", encoding="utf-8") as file:
6    writer = csv.writer(file)
7    writer.writerow(["fruit"])
8    for fruit in fruits:
9        writer.writerow([fruit])

The newline="" argument matters. Without it, some platforms can produce extra blank lines in the output.

Write Multiple Columns From a List of Rows

If each item already represents a row, writerows is a natural fit.

python
1import csv
2
3rows = [
4    [1, "Alice", 91.5],
5    [2, "Bob", 88.0],
6    [3, "Carla", 95.2],
7]
8
9with open("scores.csv", "w", newline="", encoding="utf-8") as file:
10    writer = csv.writer(file)
11    writer.writerow(["id", "name", "score"])
12    writer.writerows(rows)

This pattern is easy to read and works well when the order of columns is already fixed.

Use DictWriter for Named Fields

For data with named columns, csv.DictWriter is usually safer because it makes the schema explicit.

python
1import csv
2
3records = [
4    {"id": 1, "name": "Alice", "score": 91.5},
5    {"id": 2, "name": "Bob", "score": 88.0},
6]
7
8fieldnames = ["id", "name", "score"]
9
10with open("scores_dict.csv", "w", newline="", encoding="utf-8") as file:
11    writer = csv.DictWriter(file, fieldnames=fieldnames)
12    writer.writeheader()
13    writer.writerows(records)

This is easier to maintain than remembering that column index 2 means score. It also makes missing or misspelled fields easier to spot during review.

Let the Module Handle Quoting

CSV gets messy as soon as values contain commas, quotes, or newlines. Do not try to escape those characters by hand.

python
1import csv
2
3rows = [
4    ["name", "comment"],
5    ["Alice", "contains,comma"],
6    ["Bob", 'contains "quotes"'],
7]
8
9with open("comments.csv", "w", newline="", encoding="utf-8") as file:
10    writer = csv.writer(file, quoting=csv.QUOTE_MINIMAL)
11    writer.writerows(rows)

The csv module knows when values need quotes and how embedded quotes must be escaped. Manual string joining is one of the fastest ways to create malformed output.

Stream Large CSV Exports

If the export is large, do not build a massive list first unless you have to. Write rows incrementally from a generator or iterator.

python
1import csv
2
3
4def generate_rows(total):
5    for index in range(total):
6        yield [index, f"user_{index}", index % 2 == 0]
7
8
9with open("users.csv", "w", newline="", encoding="utf-8") as file:
10    writer = csv.writer(file)
11    writer.writerow(["id", "username", "is_active"])
12    writer.writerows(generate_rows(100000))

This keeps memory usage stable even for big exports.

Validate Row Shape Before Writing

CSV is forgiving, which means bad data can quietly produce confusing files. A short validation step can catch inconsistent row lengths before you hand the file to another system.

python
1def validate_rows(rows, expected_columns):
2    for index, row in enumerate(rows):
3        if len(row) != expected_columns:
4            raise ValueError(f"Row {index} has {len(row)} columns, expected {expected_columns}")
5
6
7rows = [
8    [1, "Alice", 91.5],
9    [2, "Bob", 88.0],
10]
11
12validate_rows(rows, 3)

That is especially useful when rows are assembled from several upstream sources.

Common Pitfalls

The most common mistake is building CSV lines manually with ",".join(...). That fails as soon as a value contains a comma, a quote, or a newline.

Another issue is forgetting newline="" when opening the file. The output may look fine in one environment and contain blank lines in another.

Developers also mix row lists and dictionaries without defining a stable schema. The result is a file whose columns shift over time.

Finally, large exports can become memory-heavy if you build every row first. Stream the rows when the dataset is large or generated on demand.

Summary

  • Use Python's csv module instead of manual string concatenation.
  • Match the writer style to the list shape: flat values, row lists, or dictionaries.
  • Always open CSV files with newline="" and an explicit encoding.
  • Let the module handle quoting for commas, quotes, and newlines inside values.
  • Stream large exports and validate row shape when reliability matters.

Course illustration
Course illustration

All Rights Reserved.