Write list to CSV in Python

A CSV file is a text file used to store data in tabular format and is compatible with Excel. It is used to store multiple values separated by a comma. If you want write list to any file, you can refer write list to file in Python.

In this article, we will write a list to a CSV file in Python.

Using the write() function to write a list to a CSV file

In this method, we will first join all the elements of the list using the join() function. This will return a string, which we can write to an external file.

To create an external CSV file, we will use the open() function in write mode to open the required file. We will then use the write() function to write the contents of the created string to this file.

This method is generally used only for single-dimensional lists since it writes everything in a single row.

See the code below.

Output:

Using the csv module to write a list to a CSV file

The csv module is used for reading and writing CSV files efficiently in Python.

To use this module, first, we will open the required CSV file in write mode using the open() function. Then we will proceed to use the csv.writer() function, which creates a writer object that allows us to write the list as a delimited string in the file. We can use a few parameters with this function.

  • The quoting parameter is used to set whether the elements need to be quoted in the final file or not. . It accepts csv.QUOTE_NONE, csv.QUOTE_ALL, and other similar values.
  • We can set the character to be used as the quotes using the quotechar parameter.
  • We can specify the delimiter character using the delimiter parameter.
  • The escapechar parameter can be used to escape the delimiter character.

Finally, to write the list, we will use the writerows() function which writes all the data to the file in one go.

For example,

Output:

In the above example,

  • The newline parameter in the open() function is set to an empty character. This is because the writer() function automatically adds a new line, so to avoid an extra empty line we do this.
  • The writerows() function writes the nested list to the CSV file as rows.
  • If we wish to write each row individually, we can use the writerow() function.

To deal with quotes in the final file, we can use the quoting parameter in the writer() function as discussed earlier. We will set the value of this parameter to csv.QUOTE_ALL. We can additionally set the character to be used as quotes using the quotechar parameter.

See the code below.

Output:

Notice how the elements all have quotes in the final file. We can similarly set the value of this parameter to csv.QUOTE_NONNUMERIC, csv.QUOTE_MINIMAL, csv.QUOTE_NONE as per the user requirements.

Using the numpy module to write a list to a CSV file

The numpy module is used in Python to deal with arrays and different functions related to arrays. We can use different functions from this module to write the list to a CSV file.

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

This is probably the most efficient and convenient method available. It can export our desired list to a CSV file.

This function also takes a lot of parameters to customize the final output.

  • We can provide the required character to separate the columns using the delimiter parameter.
  • To write a given string at the start, we can use the headers parameter.
  • Similarly, to write something at the end, we can use the footer parameter.
  • The encoding parameter is used to encode the file.
  • We can specify the format of the elements using the fmt parameter.

In the example below, we will write a list to a CSV file using this method.

Output:

In the above example,

  • We specified the format as integers by setting the fmt parameter as %d since all elements were integers.
  • The delimiter character was set to a comma.

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

The tofile() function in the numpy module is generally used for quick storage of data in binary or text files. It can write a list to a CSV file. However, the final output will be in a single line.

The sep and format parameters can be used with this function to provide the delimiter character and the format of the elements.

See the code below.

Output:

In the above example,

  • Everything is stored in a single line and not in rows.
  • We first had to export the list to an array using the numpy.array() function.

Using the pandas module to write a list to a CSV file

The pandas module has the to_csv() function, which can export a pandas DataFrame to a CSV file.

In this method, first, we will have to export our list to a DataFrame object, which will further be saved in an external CSV file.

This method is very helpful when we have to write multiple lists to a CSV file. It also allows us to provide column names and an index in the final file by default.

For example,

Output:

There are numerous parameters, which we can use with this function to customize the final file.

  • The sep parameter can set the delimiter for the final file.
  • The columns parameter can specify which columns are to be written in the final file.
  • We can specify the required encoding using the encoding parameter.
  • The headers parameter can specify the column names.
  • The index and index_label parameters are used to provide the index for rows or the column label to be used as the index.

Related Posts

  • How to comment out multiple lines in python
    16 October

    How to comment out multiple lines in python

    Table of ContentsMultiple Line Comments in PythonUsing the # characterUsing triple quotesUsing IDEs and Text Editors In this article, we will see about how to comment out multiple lines in python. The concept of comments is present in most programming languages. We use comments for documentation purposes. The compiler ignores them, but the user can […]

  • Get variable name as String in Python
    01 October

    How to get variable name as String in Python

    Table of ContentsWhat are variable names in Python?How to get a variable name as a string in Python?In Python 2.xIn Python 3.x In Python, there are several ways to convert a string to a variable name, but the reverse process is not exactly utilized so often in the programming world. This article focuses on how […]

  • Python print percent sign
    30 September

    Print percentage sign in python

    Table of ContentsIntroductionPrint the Percentage Sign in PythonUsing the %% characterUsing the format() functionUsing the f-string Introduction In this tutorial, we will see how to print percentage sign in python. The modulus operator (%) or the percentage sign has multiple usages in Python. We use this operator to calculate the remainder for the division between […]

  • Print blank line in Python
    23 September

    Print blank line in Python

    Table of ContentsWhat is a blank line in Python?Ways to print blank line in PythonUsing an empty print() functionUsing the print() function with newline characterUsing the print() function with an empty stringUsing the print() function with the sep parameterWays to print multiple blank lines in PythonUsing the print() function with multiple newline charactersUsing the print() […]

  • Python add commas to number
    11 September

    Python add commas to number

    Table of ContentsUsing the format() function to add commas to numbers in PythonUsing the fstrings to add commas to numbers in PythonUsing the regular expressions to add commas to numbers in PythonUsing the locale module to add commas to numbers in Python Python allows us to format values to get the final result in our […]

  • 10 September

    Change the font size of title in Matplotlib

    In Python, there are a lot of libraries that are used for data visualization. One of the libraries is the Matplotlib library. The Matplotlib library is a very good library when it comes to data visualisation in python. With the help of this library, many types of graphs and visual representations of the data can […]

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.