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.

Was this post helpful?


import_contacts

You may also like:

Related Posts

  • 25 June

    Convert Roman Number to Integer in Python

    Table of ContentsHow to Convert Roman Number to Integer in PythonHow to convert roman number to integer in python?Using the if...else statement to convert roman number to integer in Python.Using classes and a dictionary to convert roman number to integer in Python.Using the roman module to convert roman number to integer in Python.ConclusionWas this post […]

  • 11 June

    Remove Single Quotes from String in Python

    Table of ContentsRemove single quotes from string in Python.How to remove single quotes from string in Python?Using the replace() function to remove single quotes from string in Python.Using a for loop to remove single quotes from string in Python.Using the join() function to remove single quotes from string in Python.Using the re module functions to […]

  • 11 June

    Escape Backslash Character in Python

    Table of ContentsEscape backslash character in python.How to use escape backslash character in python?Using the escape backslash character in python to represent whitespace characters.Using the escape backslash character in python to turn special characters into ordinary characters.Using the escape backslash character in f-strings in Python.Using the escape backslash character in raw strings in Python.Was this […]

  • 11 June

    Break out of function in Python

    Table of ContentsBreak out of function in PythonHow to break out of function in Python?Using the return statement to break out of function in PythonUsing the try and except block to break out of function in PythonUsing the sys.exit() function to break out of function in PythonConclusionWas this post helpful? In this post, we will […]

  • 11 June

    Check if Object Is Iterable in Python

    Table of ContentsWhat are iterables in Python?How to check if object is iterable in Python?Using the iter() function to check if object is iterable in PythonUsing the for loop to check if object is iterable in PythonUsing the isinstance() function to check if object is iterable in PythonConclusionWas this post helpful? In this post, we […]

  • 11 June

    Save Numpy Array as Image in Python

    Table of ContentsSave numpy array as image in PythonHow to save numpy array as image in Python?Using the PIL library to save numpy array as image in PythonUsing the matplotlib.image library to save numpy array as image in PythonUsing the opencv library to save numpy array as image in PythonUsing the imageio library to save […]

Leave a Reply

Your email address will not be published.

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.