Program to Convert Array to CSV in Python

I was working on a project where I had to export a dataset from Python into a CSV file so that my team could analyze it in Excel. The dataset was stored in arrays, and the challenge was to quickly and efficiently convert these arrays into a CSV format.

If you have ever worked with Python arrays or NumPy arrays, you know how common it is to share data across different tools. CSV (Comma Separated Values) is one of the simplest and most widely used formats for this purpose.

In this tutorial, I will show you multiple ways to convert an array to a CSV file in Python. I’ll explain each method step by step, share my firsthand experience, and provide complete code examples.

Convert Arrays to CSV in Python

I often deal with structured data in Python, and arrays are one of the most common data structures. But arrays alone are not easy to share with non-developers.

CSV files, on the other hand, can be opened in Excel, Google Sheets, or even a simple text editor. They are lightweight and portable.

By converting arrays to CSV, you can:

  • Share Python data with business teams in a format they already understand.
  • Store large datasets in a structured format for later use.
  • Import/export data between Python and other tools like Excel, R, or SQL databases.

Methods to Convert an Array to CSV in Python

There are several ways to achieve this. I’ll cover the most practical ones:

1 – Convert Array to CSV Using Python’s csv Module

The first method I usually try is the built-in csv module. It doesn’t require any external libraries and works well for small to medium datasets.

Here’s an example where I have a 2D Python array of US city populations, and I want to save it as a CSV file.

import csv

# Sample 2D array: City and Population data
array_data = [
    ["City", "Population"],
    ["New York", 8419600],
    ["Los Angeles", 3980400],
    ["Chicago", 2716000],
    ["Houston", 2328000],
    ["Phoenix", 1690000]
]

# Writing array to CSV
with open("us_cities.csv", mode="w", newline="") as file:
    writer = csv.writer(file)
    writer.writerows(array_data)

print("CSV file created successfully using csv module.")

You can refer to the screenshot below to see the output.

array to csv python

When you open the us_cities.csv file, you will see the array neatly stored in rows and columns.

This method is simple, but if you’re working with numerical arrays (like from NumPy), you might prefer NumPy’s built-in methods.

2 – Convert Array to CSV Using NumPy savetxt()

If you’re already using NumPy, Python’s savetxt() function is my go-to method. It’s fast and handles numerical arrays very well.

Here’s an example where I save a 2D NumPy array of temperatures in different US states.

import numpy as np

# Create a 2D NumPy array
temperature_data = np.array([
    [75, 80, 85],
    [60, 65, 70],
    [55, 58, 62]
])

# Save array to CSV
np.savetxt("temperature_data.csv", temperature_data, delimiter=",", fmt="%d")

print("CSV file created successfully using NumPy savetxt().")

You can refer to the screenshot below to see the output.

python array to csv

In this case, each row of the array becomes a row in the CSV file. The delimiter="," ensures values are separated by commas.

If you want headers, you can add them like this:

np.savetxt("temperature_data.csv", temperature_data, delimiter=",", fmt="%d", 
           header="Day1,Day2,Day3", comments="")

3 – Convert Array to CSV Using Pandas

In many of my projects, I use Pandas because it makes working with tabular data extremely easy. Pandas can convert arrays into DataFrames and then export them directly to CSV.

Here’s an example where I store sales data for different US states.

import pandas as pd
import numpy as np

# Create a NumPy array
sales_data = np.array([
    [1200, 1500, 1700],
    [2000, 2100, 2500],
    [1800, 1900, 2200]
])

# Convert array to DataFrame
df = pd.DataFrame(sales_data, columns=["Q1", "Q2", "Q3"], 
                  index=["California", "Texas", "Florida"])

# Save DataFrame to CSV
df.to_csv("sales_data.csv")

print("CSV file created successfully using Pandas.")

You can refer to the screenshot below to see the output.

python write array to csv

The resulting CSV file will have both column headers and row labels, making it much easier to interpret.

4 – Convert Array to CSV Using NumPy tofile()

Another quick method I sometimes use is tofile(). It’s not as flexible as savetxt(), but it’s useful when you just want a raw dump of array data into a CSV.

import numpy as np

# Create a simple array
array_data = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

# Save using tofile()
array_data.tofile("simple_array.csv", sep=",")

print("CSV file created successfully using NumPy tofile().")

This method is fast, but it doesn’t support headers or formatting. So I use it only for quick exports.

Best Practices When Exporting Arrays to CSV

From my experience, here are a few important tips:

  • Choose the right method: Use csv for simple lists, savetxt() for numeric arrays, and Pandas for structured/tabular data.
  • Add headers: Always include headers when sharing with non-technical users. It makes the CSV much easier to understand.
  • Check delimiters: In the USA, commas are the standard delimiter, but sometimes you may need tabs (\t) or semicolons (;) depending on the system.
  • Encoding matters: If your array has special characters (like city names with accents), save the file with encoding=”utf-8″.

So these are four different ways to convert an array to a CSV file in Python.

  • The CSV module is simple and built-in.
  • NumPy’s savetxt() is great for numerical arrays.
  • Pandas is the most powerful option for structured data.
  • NumPy tofile() is fast but limited.

I use Pandas most of the time because it gives me flexibility with headers and indexes. But if I just need a quick export, savetxt() works perfectly.

You can read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.