Python

Python List to CSV

The file format known as CSV (Comma Separated Values) is used to store tabulated data in plain text, much like a spreadsheet or a database. Python has a built-in module called CSV that enables the reading and writing of CSV files. Python has two libraries that allow us to write to or create CSV files. The csv.writer() and csv.DictWriter() functions. In Python, lists are among the most popular and commonly used data structures. In this post, we’ll teach how to use Python to create a CSV file from a list.

What is a List Object in Python?

A python list is an orderly arrangement of elements that can be modified. The elements or values that make up a list or are stored inside a list are referred to as its items. When working with numerous connected values, lists are a useful tool. They give you the ability to streamline your code, perform the same operations on several values at once, and keep related data together.

What is CSV in Python?

A large amount of data in tabular form (numbers and text) can be stored in this format, in plain text, making it very useful. Each row or horizontal line in the data represents a single record of data and each record is made up of single or multiple fields/columns, separated by commas. Microsoft Excel can also be used to open the CSV file.

How to Convert or Write a List Object to CSV in Python?

Python offers four basic methods for creating a CSV file from a list and a list of lists.

  1. Write the list to the file using the writerows() function on the CSV writer object after importing the csv module into Python.
  2. Create a DataFrame after importing the pandas library, and then use the DataFrame function “DataFrame.to csv()” to write your DataFrame to a file.
  3. After importing the NumPy library, create a NumPy array, and then use the “numpy.savetxt()” method to save the data to a CSV file.
  4. Use the file I/O functionality of python for a pure Python approach that doesn’t need a module.

In the section below we will explain each method along with practical implementation in the form of examples.

Method#1: Converting a List to a CSV File Using CSV Module

Python’s csv module makes it simple to read and write CSV files. Using the open() function, we will first open the necessary CSV file in write mode to use this module. Then, using the csv.writer() function, we can write the python list object as a delimited string into a file by creating a writer object. With this function, we may make use of a few parameters.

Example#1: Convert a List Object to a CSV Row

Here, we will write the Python code for writing a list to a csv row. We will import a csv module first. A list will be created with data elements. Then, we will create our ‘file_name.csv’. The “w+” mode will be used to write the csv file. You can obtain the values/elements in the newline by using newline = ‘ ’. The writerows() will be used to write all the rows to the file, whereas “csv.writer(file)” writes all the data of the list to the CSV file.

The output is displayed to us in row format:

Example#2: Convert a List Object to a CSV Header

We will now see how to convert a list to a CSV header

In this example, we will take a variable after loading/importing the csv module. Then, we will use the open() function to open the file. The csv writer method will be used to write/convert the list object to a CSV file. Using writerow(), we will write the list’s data in the form of rows to a CSV file. Again, we will use the writerows() function to write the header of the list data.

The header and list elements are both visible in our csv file:

Method#2: Converting a List to a CSV File Using Pandas Module

To use this method, we must first convert the list object to a DataFrame, which will then be converted to an external CSV. This method is really useful when we need to write more than one list or list of lists to a .csv file. Additionally, it enables us to automatically include a column index and column names in the resultant file.

Example#1: Using to_csv() Function

A Pandas DataFrame can be created from a list of lists, giving you access to useful functions like the to_csv() method. The benefit of employing this method is that no additional libraries need to be imported.

Output File:

These parameters can be used with this function to modify the output file:

  • The output file’s delimiter can be set using the sep parameter.
  • The output file’s columns can be specified using the columns parameter.
  • By using the encoding parameter, the required encoding can be specified.
  • We can specify column names using the headers argument.
  • To specify the row index or the column names to serve as the index, the index label and index parameters can be used.

Method#3: Converting a List to a CSV File Using Numpy Module

Python’s and machine learning and data science functionalities are built around NumPy. NumPy arrays are used by even Pandas to implement essential features. The Numpy module provided some functions which we can use to write the list object to CSV. This method is most effective when you simply have numerical data. Otherwise, it requires complex data type transformations, which is not recommended.

Example#1: Using the savetext() Function

Using NumPy’s savetext() function, you may create a CSV file from a list of lists. The NumPy array will be passed as an input to the function.

Output File:

In the script above,

  • Since all of the elements were numbers, we set the fmt argument as %d to specify the format as integers.
  • The comma is specified as the delimiter character.

Example#2: Using the numpy.tofile() Function

The NumPy module’s tofile() function is typically used for rapid data storage in text files or binary files. A list can be written to a CSV using the tofile() function. The output, however, will be one line. With this function, you can specify the format of the data and the delimiter character by using the format and sep parameters.

Output File:

As can be seen, instead of rows, everything is arranged in a single line. It is necessary to first convert the list to an array before using the tofile() function.

Method#4: Converting a List to CSV Without Importing Modules

We can use standard or basic Python implementation instead of importing any libraries to create a CSV file from a list of lists because it’s simple and effective. However, if at all possible, you ought to rely on libraries to complete the task for you.

Example:
The file object will first be opened. The next step is to iterate over the rows and elements of the rows and then write all elements to the file.

Output File:

To create a CSV file format, add a comma after each element. The newline character “\n” should be placed after each row.

Conclusion

In this tutorial, we first saw the introduction to CSV and list objects in pandas. Then we discussed how the list can be converted to a CSV file in python. We explained four methods to create a CSV file from a list or list of lists. In the first method, we used the csv module. In the second method, we used the pandas module for converting the list into a dataframe and then into csv. In the third method, we used savetext() and tofile() functions of the Numpy module. In the last method, we implemented an example to create CSV from a list object without importing a module.

About the author

Aqsa Yasin

I am a self-motivated information technology professional with a passion for writing. I am a technical writer and love to write for all Linux flavors and Windows.