How do i convert a list to a csv file in python?

CSV [Comma Separated Values] is a file format that is used to save the data in the tabular format. Python provides various functions to convert any data type to csv data or file. Some functions are inbuilt and some functions are third-party libraries.

To convert the list to csv in Python, use one of these approaches.

  1. Using the inbuilt Python CSV module.
  2. Using Pandas to_csv[] method.
  3. Using numpy.savetxt[] function.

Python 3 comes with an inbuilt CSV module, so you need to import the module in your file to use its functions.

To install numpy, type the following command. I am assuming that you have installed or upgraded pip, which is a Python package manager.

python3 -m pip install numpy

To install the Pandas library, type the following command.

python3 -m pip install pandas

Using the inbuilt Python CSV module

Python csv module provides csv.writer[] method, which returns the write object, and then we can call the writerow[] and writerows[] functions to convert list or list of lists the csv file.

To create a file, use Python with statement, which does not require closing the file since with statement does the job for us.

import csv

cols = ["Character Name", "Series Name", "Profession", "Age"]

rows = [["Mando", "Mandalorian", "Bounty Hunter", 35],
        ["Grogu", "Mandalorian", "Jedi Master", 50],
        ["Eleven", "Stranger Things", "Kid", 14],
        ["Jon", "Game of Thrones", "King", 30],
        ["Ross", "Friends", "Paleontologist", 35]]

with open['shows.csv', 'w'] as f:

    # using csv.writer method from CSV package
    write = csv.writer[f]

    write.writerow[cols]
    write.writerows[rows]

In this example, first, we have imported the csv module. Then we have defined two lists.

  1. rows
  2. columns

The cols list defines the columns of the csv file, and rows are a list of lists that will create rows of the csv file. Use the with statement to open a shows.csv file, and if it does not exist, it will create for us and write the rows and cols to the csv file.

If you run the above code, then in your current directory, you will see a shows.csv file. If you open the file, then you will see that it is filled with comma-separated values. So this is the first way to convert a list to csv.

Using Pandas to_csv[] function

To convert the list to csv, we need to convert from list to dataframe and then use the to_csv[] function to convert dataframe to a csv file.

import pandas as pd

char_name = ["Mando", "Grogu", "Eleven", "Jon", "Ross"]
series_name = ["Mandalorian", "Mandalorian",
               "Stranger Things", "Game of Thrones", "Friends"]
profession = ["Bounty Hunter", "Jedi Master", "Kid", "King", "Paleontologist"]
age = [35, 50, 14, 30, 35]

dict = {"Character Name": char_name, "Series Name": series_name,
        "Profession": profession, "Age": age}

df = pd.DataFrame[dict]

df.to_csv['shows.csv']

In this example, we have first imported pandas library and then define the four lists and map it with its column using a dictionary. Then use the pd.DataFrame[] function to convert it into DataFrame and then use the to_csv[] function to convert the DataFrame to CSV file.

Using numpy.savetxt[] function

Numpy savetxt[] function save an array to a text file. We can also use the savetxt[] file to save the data into csv file.

import numpy as np

data = [ ["Mando", "Grogu", "Eleven", "Jon", "Ross"],
         ["Mandalorian", "Mandalorian","Stranger Things", "Game of Thrones", "Friends"],
         ["Bounty Hunter", "Jedi Master", "Kid", "King", "Paleontologist"],
         [35, 50, 14, 30, 35] ]

np.savetxt["shows.csv", data, delimiter=", ", fmt="% s"]

If you run the above code, you will see the shows.csv file in your current project folder.

That is it for converting Python list to the csv file.

See also

Python list to array

Python list to tuple

Python list to string

Python list to json

Python list to dataframe

Python list to dictionary

How do I make a list in csv?

The most common method to write data from a list to CSV file is the writerow[] method of writer and DictWriter class. Example 1: Creating a CSV file and writing data row-wise into it using writer class.

How do you convert a list in Python?

To convert a list to a string, use Python List Comprehension and the join[] function. The list comprehension will traverse the elements one by one, and the join[] method will concatenate the list's elements into a new string and return it as output.

How do you convert a list to a comma separated string in python?

Use str..
a_list = ["a", "b", "c"].
joined_string = ",". join[a_list] Concatenate elements of `a_list` delimited by `","`.
print[joined_string].

How do I save a list in a text file Python?

The below steps show how to save Python list line by line into a text file..
Open file in write mode. Pass file path and access mode w to the open[] function. ... .
Iterate list using a for loop. Use for loop to iterate each item from a list. ... .
Write current item into the file. ... .
Close file after completing the write operation..

Chủ Đề