How to Write List To CSV Python

In this Python tutorial, I will show you how to write a list using CSV Python. This is the command task in data science.

When I was working on the dataset for machine learning, I had to save it to a CSV file after analyzing it. I used the Pandas library for data analysis, so I had to save the dataset in the dataframe to a CSV file.

Then, I used the pandas to_csv() function to save it in a CSV file; additionally, while researching on the internet, I found two more methods to save the list to CSV, which I explained in this tutorial.

Write List To CSV Python Using Pandas

Pandas is a Python-based library for data manipulation and analysis. To learn more about pandas, visit this page: Pandas Tutorial.

As you know, Pandas has a data structure called a dataframe, which stores data as rows and columns. So, Pandas has some functions that allow you to save the dataframe to different file formats, like CSV.

Pandas provide a function called to_csv(), which saves the dataframe in a CSV file.

The syntax is given below.

dataframe.to_csv('file_name.csv')

Where,

  • dataframe: It is the dataframe containing 2-dimensional data which you want to write or save to a CSV file.
  • to_csv(‘file_name.csv’): This function is called on the data frame and accepts an argument file name with an extension of CSV. This function saves or writes the data of the dataframe to a specified CSV file name in your directory.

For example, Open the command prompt on your computer, type ‘python’, and hit enter to open the Python shell.

READ:  How to Sum Elements in List in Python using For Loop

After opening the Python shell, import the panda’s library using the code below.

import pandas as pd

Create a list you want to save as CSV, as shown below.

daily_task = ['Wake up at 5:00 AM', 'Take a Shower', 'Prepare breakfast', 'Start remote work']

In the above, a list named daily_task is created. To save this list as CSV, convert it into a dictionary using the code below.

task_dict = {'task': daily_task}

In the above, a dictionary named task_dict was created, which contains the key ‘task’ and the value list of ‘daily_task’.

The to_csv() method works on a dataframe, so convert the task_dict to a dataframe using the code below.

task_df = pd.DataFrame(task_dict)

Now call the to_csv() with the file name daily_task.csv, as shown below.

task_df.to_csv('daily_task.csv')
Write List To CSV Python Using Pandas

Here, look at this line of code: ‘task_df.to_csv(‘daily_task.csv’)’; this line saves all the data of the task_df dataframe into a daily_task.csv file on your system. It creates a new file named daily_task.csv on your system and writes all the data of dataframe task_df into it.

The file is saved on my computer at ‘C:\Users\saura’, as shown in the picture below.

Viewing List To CSV Converted File

So, to view it, open the daily_task CSV file, as shown in the above picture. You can see all the data you have specified in the list.

This is how to save a list to CSV in Python using the Pandas to_csv() function.

Python Save List to CSV Using CSV Module

The ‘CSV’ module is part of the Python library, which has a method called csv.writer(), which allows you to write a list of data in a CSV file.

For example, take the list of daily_tasks you created in the above section.

READ:  How to Square a List in Python

Import the ‘csv’ module as shown below.

import csv

daily_task = ['Wake up at 5:00 AM', 'Take a Shower', 'Prepare breakfast', 'Start remote work']

Now, use the code below to save the daily tasks on the list into CSV.

with open('task.csv', 'w', newline='') as f:
     
    write = csv.writer(f)
    write.writerows([daily_task])

In the above code, open the CSV file name task.csv in write mode by specifying ‘w’; if the file task.csv doesn’t exist, it creates a new one in your default directory.

After that, it creates a csv.writer object using the write = csv.writer(f) method. Then, it takes each task from the daily_task and writes it to the CSV file task.csv using the method writerrow().

Python Save List to CSV Using CSV Module

As you can see in the above picture, the list of daily tasks is written or saved to a file called task.csv. But it saves the list of functions row-wise with a task.csv file. That’s because our goal is to know how to save list csv.

This is how to save a list to CSV using the CSV module.

Python Write List to CSV Using Numpy

The Python Numpy library is used for large arrays or multi-dimensional datasets. Its functions allow you to perform some operations on these arrays.

Let’s take an example. First, create a list of products with their names and categories, as shown below.

import numpy as np

products = [
    ['Apple', 'Fruit', '10', '2.5'],
    ['Banana', 'Fruit', '15', '1.8'],
    ['Milk', 'Dairy', '5', '3.2'],
    ['Bread', 'Bakery', '20', '2.0'],
    ['Eggs', 'Dairy', '30', '1.5'],
    ['Chicken', 'Meat', '8', '5.7']
]

To save the list of products to a CSV file, Numpy has a function called savetxt(), which saves the two-dimensional array into a text file.

READ:  Merge Dictionaries in Python (8 different methods)

If you want to know how np.savetxt() function works, then read this tutorial Np.savetxt() Function In Python [5 Examples] – Python Guides

Use the np.savetxt() function to save a list of products to a CSV file using the code below.

np.savetxt("products.csv",
        products,
        delimiter =", ",
        fmt ='% s')

In the above, the file name product.csv is passed to the np.savetxt() function as the delimiter, which separates the list of products in the file; the delimiter is a comma (, ), and the format is ‘$ s’.

Python Write List to CSV Using Numpy

The above picture shows the file product.csv being opened in MS Excel. This file was created using the np.savetxt(). It contains a table-formatted list of products.

Using the np.savetxt() function, you can save the list to a different format.

This is how to write a list to CSV in Python using the savetxt() function of the Numpy library.

Conclusion

In this Python tutorial, you learned how to write a list using CSV Python, the padas, the numpy library, and the CSV module.

You may like to read: