Python write array to CSV

Write array to CSV in Python

A CSV file is a simple text file, with data separated by commas. It can represent tabular data and viewed as spreadsheets.

An array is used to store a collection of elements under a single name. We use the numpy module to deal with arrays in Python.

We will discuss different methods on how to write array to CSV file.

Using the pandas.to_csv() function to write array to CSV file

The to_csv() function exports a pandas DataFrame to a CSV file of the desired name. We can create a DataFrame using an array and then write this DataFrame to a CSV file.

The advantage of this method is that we can view the DataFrame and check how it looks before exporting it to a CSV file.

See the following code.

Output:

In the above example, we were able to save an array in a CSV file. Note that this function automatically adds the column names and the index column to the file.

Numerous parameters can be used with this function. Some of them are discussed below.

  • The sep parameter is used to set the field delimiter for the file. By default, it is a comma.
  • The index_label can be used to give the column a label, which is to be used as the index.
  • The headers parameter sets the column names for the file.
  • For floating numbers, we can specify the format using the float_format parameter.

We will use some of these parameters in the example below.

Output:

In the above example, we added the column names using the header parameter and also provided the label for the index column using the index_label parameter.

Using the numpy.tofile() function to write array to CSV file

The tofile() function can write a numpy array to a binary or text file. It is generally used for quick storage of the data. It also provides the sep and format parameter to set the delimiter character and string format. Since we are saving the array in a CSV file, we will need to specify the sep parameter as a comma.

However, it is not considered a convenient method to export an array to a CSV, because precision is lost while using this method, and everything is stored in a single line.

For example,

Output:

In the above example, one can observe that the final output in the file is in a single line.

Using the numpy.savetxt() function to write array to CSV file

The numpy.savetxt() function can export an array to a text file. It is generally used only with one or two dimensional arrays and does not give the desired output with higher dimensional arrays. This method provides a lot of parameters to get the final file in CSV format.

  • The delimiter parameter can be used to provide the character or string to separate the columns.
  • The header parameter is used to write a string at the start of the file.
  • To write something at the end of the file we use the footer parameter.
  • We can use the encoding parameter to encode the final file.
  • The fmt parameter specifies the format for the elements of the array in the file.

In the following example, we will use this function to write array to CSV file.

Output:

In the above example, we specified the delimiter character as a comma because the final file needs to be a CSV file. The fmt parameter was set as %d because our array contains only integers. Also notice that no columns or indexes are added to the file by default.

Using the file-handling methods to write array to CSV file

We can create a file object and use it to write array to CSV file. However, it is not advisable to use this method since it requires a lot of memory and can get complicated with large arrays.

For example,

Output:

In the above example, we first converted the array to a list. Then we joined the elements of the list with a newline character using the join() function and wrote these elements to a CSV file by creating a file-object using the open() function.

Using the writerows() function to write array to CSV file

The csv module has classes and methods available to read and read CSV files. We can create a writer object and use the writerow() function to write the array to a CSV file. We will also create a file object using the open() function to be used in the writer() function.

We can use the delimiter in the writer() constructor to specify the separator character.

We will use this method in the following example.

Output:

That’s all about Python write array to CSV.

Related Posts

  • Python check for null
    17 November

    How to check for null in Python

    Table of ContentsHow to check if a variable is NULL in Python?Using the is operator to check if a variable is NULL in Python.Using the if condition to check if a variable is NULL in Python.Using the not equal to operator to check if a variable is NULL in Python. This article demonstrates the different […]

  • Sort dictionary by value in Python
    17 November

    Sort dictionary by value in python

    Table of ContentsHow to sort sort dictionary by value in Python?Using for loop along with the sorted() function.Using the sorted() function to sort dictionary by value in Python.Using operator.itemgetter() function to sort sort dictionary by value in Python.Using lambda function to sort sort dictionary by value in Python.Using the OrderedDict() method to sort sort dictionary […]

  • Get class name in Python
    17 November

    Get class name in Python

    Table of ContentsHow to get the attributes of an object?Get Class name in python using the __class__ attribute Get Class name in python using type() functionConclusion While working with objects in python, several times we need to get their class name. In this article, we will discuss several ways to get the class name of an […]

  • Python print to file
    17 November

    How to Print to File in Python?

    Table of ContentsThe print() function in pythonHow to Print to file in python?Print to file using the file parameter in the print functionPrint to file by redirecting standard outputConclusion We use the print() function in python to print any text to standard output. In this article, we will see how we can use the print() […]

  • Python absolute path
    17 November

    Get Absolute Path in Python

    Table of ContentsWhat is an absolute path to a file? How to get absolute path in PythonUse abspath to get the absolute path to file use pathlib module to get the absolute path to file Conclusion We often use files to store the outputs of our programs in permanent storage. Generally, we work with relative […]

  • Python sort list of lists
    17 November

    Sort List of Lists in Python

    Table of ContentsSort List of Lists Using the sort() Method in PythonUsing the itemgetter() methodUsing Lambda FunctionsSort List of Lists Using the sorted() Function in PythonSort lists of lists on the basis of the length of the inner listsConclusion Several times we use 2-D lists or lists of lists in our programs to represent a […]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.