**How to write a NumPy array to a CSV file in Python?**

To write a NumPy array to a CSV file, use the `np.savetxt()`

function and pass the filename as a string, as well as the array into it. Optionally, you can specific the file format, the delimiter such as comma or semicolon, and other arguments to obtain the desired file format.

Let’s dive into this and other approaches to “dump” a NumPy array to a CSV file.

## Method 1: np.savetxt()

To write a NumPy array to a CSV file, use the `np.savetxt(filename, array, delimiter=',')`

function and pass the filename as a string, the array, and the delimiter into it.

Here’s an example:

import numpy as np a = np.array([[1, 2, 3], [4, 5, 6]]) np.savetxt('my_file.csv', a, delimiter=',')

If you open the file, it looks like this:

All values are automatically converted into a floating point representation that may not be what you have expected.

## Method 2: np.savetxt() with format specification

The `np.savetxt()`

function allows you to specify the desired format of the values to be written in the file using the `fmt`

argument. To write a NumPy array to a file, you can use the expression `np.savetxt('my_file.csv', a, fmt='%.1f', delimiter=',')`

. Unlike the default formatting, this will not use the scientific data type notation with a gazillion precision.

Here’s the simplified code to convert the array to a formatted CSV:

import numpy as np a = np.array([[1, 2, 3], [4, 5, 6]]) np.savetxt('my_file.csv', a, fmt='%.1f', delimiter=',')

This code snippet leads to the following simplified output (CSV):

Optionally, you can specific the file format, the delimiter such as comma or semicolon, and other arguments to obtain the desired file format.

## Method 3: Pandas to_csv()

The `pandas.to_csv()`

function converts a DataFrame to a CSV file. The most simple way is to call the function on the DataFrame to be written in the file, and passing the `filename`

and index=False into it to avoid using a column header line. To obtain the DataFrame from the NumPy array, use the `pandas.DataFrame(array)`

constructor.

Here’s a minimal example:

import numpy as np import pandas as pd a = np.array([[1, 2, 3], [4, 5, 6]]) df = pd.DataFrame(a) df.to_csv('my_file.csv', index=False)

The output is the following CSV file:

## Method 4: NumPy array.tofile()

When used with a separator argument `sep`

, the NumPy `array.tofile(filename, sep=',')`

method writes the array to a file as a textual representation. The multi-dimensional array is flattened before it is written in the file.

Here’s an example for a 2D array:

import numpy as np a = np.array([[1, 2, 3], [4, 5, 6]]) a.tofile('my_file.csv', sep=',')

Output file:

To show you that the array is indeed flattened before written in the file, here’s an example for a 3D array:

import numpy as np a = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [0, 0, 0]]]) a.tofile('my_file.csv', sep=',')

Output file:

## Method 5: Vanilla Python with File I/O and Python Tricks

To write the array to a CSV in Python, you can iterate over each row in the array and use the `print()`

function’s `file`

argument to append the row to the output file.

To find a comma-separated representation of the row, simply unpack all row values into the `print()`

function using the asterisk operator `*row`

and use the separator argument `sep=','`

.

Here’s how that looks like:

import numpy as np a = np.array([[1, 2, 3], [4, 5, 6]]) with open('my_file.csv', 'w') as out: for row in a: print(*row, sep=',', file=out)

The output is as clean as it can get:

## Summary

We proposed the following five ways to write a NumPy array to a CSV file:

**Method 1**:`np.savetxt()`

**Method 2**:`np.savetxt()`

with format specification**Method 3**: Pandas`to_csv()`

**Method 4**: NumPy`array.tofile()`

**Method 5**: Vanilla Python with File I/O and Python Tricks

While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.

To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.

His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.