Write List of Lists to CSV File in Python

To write a List of Lists to a CSV file in Python:

import csv

data = [
    ["value_1", "value_2", "value_3"],
    ["value_4", "value_5", "value_6"],
    ["value_7", "value_8", "value_9"]
]

file_path = r"path to store the file\file_name.csv"

with open(file_path, "w", newline="") as file:
    csv_writer = csv.writer(file)
    csv_writer.writerows(data)

Example of Writing a List of Lists to a CSV File in Python

Step 1: Create the List of Lists

Let’s suppose that we have the following List of Lists in Python:

data = [
    ["Product", "Price", "Brand"],
    ["computer", 1200, "A"],
    ["monitor", 400, "B"],
    ["tablet", 250, "C"]
]

print(data)

The resulted List of Lists:

[['Product', 'Price', 'Brand'], ['computer', 1200, 'A'], ['monitor', 400, 'B'], ['tablet', 250, 'C']]

Step 2: Capture the path where the CSV will be saved

For example, the CSV file will be saved under the following path:

C:\Users\Ron\Desktop\Test\products.csv

Where the new CSV file will be called “products” and the file extension is .csv.

Step 3: Write the List of Lists to a CSV file

Finally, let’s apply the following code to write the List of Lists to a CSV file using Python (don’t forget to modify the path based on your needs, and place the “r” letter before the path to avoid any unicode errors):

import csv

data = [
    ["Product", "Price", "Brand"],
    ["computer", 1200, "A"],
    ["monitor", 400, "B"],
    ["tablet", 250, "C"]
]

file_path = r"C:\Users\Ron\Desktop\Test\products.csv"

with open(file_path, "w", newline="") as file:
    csv_writer = csv.writer(file)
    csv_writer.writerows(data)

Run the code (adjusted to your path) and the new “products” CSV file will be created.