Python write array to CSV [4 Methods]

In this Python article, I will explain how Python write an array to CSV file using different methods with examples. Also, I will explain how to write 2D and 3D arrays to a CSV file in Python.

To write an array to a CSV file in Python you can use functions such as savetxt, and tofile() from the NumPy library, or the to_scv() from Pandas library. We can also use csv module functions such as writerow(). The savetxt saves a 1D or 2D array to a text file, The tofile() writes array data to a file in binary format, The writer() writes a single row to the CSV file, and the to_csv() writes a pandas DataFrame to a comma-separated values (csv) file.

Methods in Python write array to CSV

There are many modules and library functions in Python that can be used to write an array to a CSV file.

  1. pandas.to_csv()
  2. csv.writerow()
  3. numpy.savetxt
  4. numpy.tofile()

Let’s see them one by one using some demonstrative examples:

Method 1: Write array to CSV in Python using pandas.to_csv()

Here, we can see how we can use pandas.csv() to write an array to CSV file in Python.

The Pandas is a powerful data manipulation library in Python that provides easy-to-use data structures and data analysis tools. One of these data structures is the DataFrame, which can be easily exported to a CSV file.

In this example of Python, we generate a sequence of numbers, reshape them into a matrix, convert that matrix to a DataFrame, and then save that DataFrame as a CSV file.

Example: Let’s take an example that will first create a 2D array and then write it to a CSV file in Python.

import pandas as pd 
import numpy as np 
array = np.arange(1,21).reshape(4,5) 
dataframe = pd.DataFrame(array) 
dataframe.to_csv(r"C:\Users\Administrator.SHAREPOINTSKY\Desktop\Work\data1.csv")

Output: We can see that the array is stored in the CSV file as the output. You can refer to the below screenshot for the output.

Python write array to CSV

This way we can easily create an array and then write it to a CSV file in Python using pandas.to_csv() function.

READ:  Python Dictionary KeyError: None

Method 2: Array to CSV Python using csv.writer()

The csv module in Python provides functionality to read from and write to CSV files. The writerow() function in the csv module will be used to write the array to a CSV file.

Scenario: Consider a situation where we have to store that into a CSV file through Python. The file is already stored as a Python array. So, to write array to csv file Python:

import csv
import numpy as np
array = np.array([['welcome'], ['to'], ['pythonguides !']])
file = open(r'C:\Users\Administrator.SHAREPOINTSKY\Desktop\Work\site.csv', 'w+', newline ='')
with file:
    write = csv.writer(file)
    write.writerows(array)

Output: In this example, we are first creating a 2D array with the help of np.array(). Then we open the file and write on it. The rows of the NumPy array are written to the CSV file, each as a separate line.

The “newline=” argument is used to ensure that the CSV writer correctly handles newline characters across different platforms.

We create a context manager that ensures the file is properly closed after its suite finishes, even if an exception is raised on the way. Inside the context manager, you create a csv.writer object which will be used to write data to the file with the help of writerows().

The output can be seen in row format in the below screenshot.

python array to csv

This way we can use the writerow() function from csv module in Python write array to csv.

Method 3: Write array to csv Python using savetxt function from NumPy library

The NumPy is a library for numerical computations in Python. It provides a function called savetxt which can be used to save an array to a text file, including CSV.

Example 1: In this example, we have an array that we have to save to a new CSV file through Python.

import  numpy as np
array = np.array([2 ,4, 6, 8, 10])
newfile = np.savetxt("header.csv", np.dstack((np.arange(1, array.size+1),array))[0],"%d,%d",header="Id,Values")
print(newfile)

Output: A one-dimensional array of integers is created using an array method from the imported numpy library.

Next, another array ranging from 1 to the size of the previously created array is generated. These two arrays are stacked along a third dimension using np.dstack() method, transforming them into a two-dimensional array. The first row of this two-dimensional array is selected.

READ:  What are the Different ways to Create Strings in Python

The selected data is then written to a CSV file, formatted as integers separated by commas, and including a header. The np.savetxt() method used for writing to the file doesn’t return any value, resulting in None being printed to the console when attempting to print the method’s output.

save 2d array to csv python

Example 2: Here, we can how to write an array to csv file using numpy.savetxt in Python

  • In this example, I have imported a module called numpy and created a variable as array and assigned array = numpy.array([[2, 4, 6],[8, 10, 12],[14, 16, 18]]).
  • I have used numpy.savetxt(“even.csv”, a, delimiter = “,”), the savetxt is the function of numpy used to save the numpy array to a file.
  • The delimiter is a sequence of characters used to specify the boundary between separate.

Source code:

import numpy 
array = numpy.array([[2, 4, 6], 
                 [8, 10, 12], 
                 [14, 16, 18]]) 
numpy.savetxt("even.csv", array, delimiter = ",")

You can refer to the below screenshot for the output how Python write array to CSV file:

2d array to csv python

This way we can use the savetxt in Python write array to csv.

Method 4: Write 2D array to csv Python using the tofile() function

The tofile function in NumPy is generally used for writing array data to a binary file. But, we can use it to write Python array to CSV file.

Example: Consider a situation where I was told to write data stored as an array in Python, to a CSV file for further procedure.

import numpy as np 
array = np.arange(1,20) 
print(array) 
array.tofile('hello.csv', sep = ',')

Output:

  • In this example, I have imported a module called numpy as np and created a variable called an array, and assigned array = np.arange(1,20).
  • The np.arange is used to create an array with the range, (1,20) as the given range.
  • The array.tofile is used to write all the items to the file object, ‘hello.csv’ is the name of the file sep = ‘,’ is the separator.

The number between the given range is shown in the below screenshot as the output.

python 2d array to csv

This way we can use the tofile method from the NumPy library in Python write array to CSV.

Different cases of Python write array to CSV file

Here, is the ways to write 2D and 3D arrays to the CSV files through Python:

Case 1: Python save 2D array to CSV

Here, we can see how to write 2Darray to CSV file in Python

  • In this example, I have imported a module called csv, and variable is created as array_2D as array_2D = [[3,6,9,12],[4,8,12,16]].
  • To open the file I have used open(“array.csv”,”w+”) as my_csv: The array.csv is the name of the file “w+” is the mode used to write the file.
  • Another variable new array is called as newarray = csv.writer(my_csv,delimiter=’,’). The CSV writer is used to insert the data into a CSV file.
  • The delimiter is a sequence of characters used to specify the boundary between separate.
  • The newarray.writerows(array_2D) is used to write each row in the csv file.
READ:  Write a Python Program to Check Whether a List Contains a Sublist

Source Code:

import csv
array_2D = [[3,6,9,12],[4,8,12,16]]
with open("array.csv","w+") as my_csv:
    newarray = csv.writer(my_csv,delimiter=',')
    newarray.writerows(array_2D)

In the below screenshot, you can see that the 2D array is stored in the csv file. You can refer to the below screenshot for the output.

python write 2d array to csv

This way we can write a 2D array to a CSV file through Python.

Case 2: Python write 3D array to CSV file

Here, we can see how Python write array to CSV file of different dimension like 3D.

  • In this example, I have imported a module called csv, and the variable is created as array_3D as array_2D = [[3,6,9,12],[4,8,12,16],[5,10,15,20]].
  • To open the file I have used with open(“array.csv”,”w+”) as my_csv: The array.csv is the name of the file “w+” is the mode used to write the file.
  • Another variable new array is called as newarray = csv.writer(my_csv,delimiter=’,’). The CSV writer is used to insert the data into a CSV file.
  • The delimiter is a sequence of characters used to specify the boundary between separate.
  • The newarray.writerows(array_3D) is used to write each row in the CSV file.

Source Code:

import csv
array_3D = [[3,6,9,12],[4,8,12,16],[5,10,15,20]]
with open("array_3D.csv","w+") as my_csv:
    newarray = csv.writer(my_csv,delimiter=',')
    newarray.writerows(array_3D)

In the below screenshot, you can see the output as the 3D array is stored in the csv file.

save 3d array to csv python

This way we can write a 3D array to a CSV file through Python.

Conclusion

In this tutorial, we have learned about the Python write array to CSV file, using different libraries and modules functions like pandas.to_csv(), csv.writerow(), numpy.savetxt, and numpy.tofile. I have explained each method with the help of some examples.

Also, I have explained how to write different kinds of arrays to a CSV file through Python such as 2D and 3D arrays.

You may like the following Python tutorials: