Array to CSV in python

·

2 min read

Before you can write to a CSV file, you'll need to import Python's built-in csv module.

import csv

Your array can be a list of lists, where each sub-list represents a row in the CSV file. Here's an example array that we'll write to a CSV file:

data = [
    ["Name", "Age", "City"],
    ["Alice", 30, "New York"],
    ["Bob", 25, "Los Angeles"],
    ["Charlie", 35, "Chicago"]
]

In this example, the first sub-list (["Name", "Age", "City"]) represents the header row of the CSV file, while the subsequent sub-lists represent the data rows.

Use Python's built-in open() function to create a file object. Use the 'w' mode to open the file for writing. If the file does not exist, it will be created.

with open('people.csv', 'w', newline='') as file:
    writer = csv.writer(file)
    writer.writerows(data)

The newline='' parameter ensures that the CSV module handles the line endings correctly across different platforms.

Putting it all together, here’s the full example:

import csv

# Define your array
data = [
    ["Name", "Age", "City"],
    ["Alice", 30, "New York"],
    ["Bob", 25, "Los Angeles"],
    ["Charlie", 35, "Chicago"]
]

# Open a CSV file in write mode
with open('people.csv', 'w', newline='') as file:
    writer = csv.writer(file)
    # Write the array to the CSV file
    writer.writerows(data)

After running this script, you'll have a people.csv file in your working directory with the following content:

Name,Age,City
Alice,30,New York
Bob,25,Los Angeles
Charlie,35,Chicago