| by Arround The Web | No comments

Python List to CSV

CSV or (Comma Separated Values) file is a widely used format for storing and exchanging tabular data. It is similar/equivalent to a spreadsheet or a database but simpler and more flexible. Python provides various modules and methods to deal with CSV data, such as the CSV module, to_csv() function, etc. These methods can easily write data from a list or dictionary to a CSV file.

This blog will provide a thorough guide on how to create a CSV file from a Python list by utilizing the following methods:

Method 1: Create CSV File From a Python List Using “write()” Method

The “open()” function is used along with the nested for loop and “file.write()” method to create a CSV from a Python list. For further understanding, consider the following code:

list1 = [['Name','Joseph', 'Anna', 'Lily'],['Age', 12, 32, 22],['Height', 5.7, 5.3, 4.9]]
with open('new.csv', 'w') as file:
    for i in list1:
        for j in i:
            file.write(str(j) + ',')
        file.write('\n')

In the above code:

  • The list is initialized, and the “open()” function is employed to open the “CSV” or comma-separated file in “w” mode.
  • The nested for loop iterates over the list and writes the list element to CSV using the “write()” method.

Output

The list has been converted into a Python CSV file.

Method 2: Create a CSV File From a Python List Using the “CSV” Module

The “csv” module supports various functions to read and write CSV files. The “csv.writer()” function is used with the “writerows()” function to create a writer object and write rows of data to that object. Let’s overview the following code for further understanding:

import csv
list1 = [['Name','Joseph', 'Anna', 'Lily'],['Age', 12, 32, 22],['Height', 5.7, 5.3, 4.9]]
with open('new.csv', 'w', newline ='') as file:
    f = csv.writer(file)
    f.writerows(list1)

Here in this code:

  • The “CSV” module is called/imported, and the list is initialized.
  • The “open()” function is utilized to open the comma-separated file named “csv” in “w” mode.
  • The “writer()” function takes the file object as an argument and creates the writer object.
  • Lastly, the “writerows()” function is used to write the specified list to a CSV file named “new.csv”.

Output

The CSV file has been created from the Python list.

Method 3: Create a CSV File From a Python List Using the “to_csv()” Function

The “to_csv()” function of the Pandas module is used to convert the Pandas DataFrame to a CSV file. This function is utilized to construct/create a CSV file from a Python list. For demonstration, take the following code:

import pandas
list1 = [['Name','Joseph', 'Anna', 'Lily'],['Age', 12, 32, 22],['Height', 5.7, 5.3, 4.9]]
df = pandas.DataFrame(list1)
df.to_csv('new.csv', index=False, header=False )

In the above example:

  • The “pandas” module is imported, and nested lists are initialized.
  • The “pandas.DataFrame()” function creates DataFrame by accepting the initialized list.
  • This DataFrame is converted into a CSV file using the “to_csv()” function.

Output

The Python list has been converted to a CSV file.

Method 4: Create CSV File From a Python List Using the “savetxt()” Function

The “savetxt()” function of the Numpy module is used to save or store an array to a text file. We can use this method to create/construct a CSV file. Here is an example code:

import numpy
list1 = [[1, 5, 10],[12, 32, 22],[5.7, 5.3, 4.9]]
arr = numpy.array(list1)
numpy.savetxt('new.csv', arr, delimiter=',', fmt='%d')

In the above code:

  • The “Numpy” module is imported.
  • The “array()” takes the list and retrieves an array object.
  • The “savetxt()” takes the file name, array, and the “delimiter” parameter as an argument to create a CSV file from the list.

Note: This method can only write a list with matching data type values otherwise TypeError is raised.

Output

The CSV file has been created successfully.

Conclusion

In Python, the “write()”, “CSV”, “to_csv()”, and the “savetxt()” methods are utilized to create a CSV file from the input list. The “write()” method is used along with a for loop and open() function to write a CSV file from a Python list. The other methods, such as the “CSV” module, “to_csv()” function of the Pandas module, and “savetxt()” function of the Numpy module, can efficiently write a CSV file from the given Python list. This guide presented a complete guide on Python list to CSV using numerous examples.

Share Button

Source: linuxhint.com

Leave a Reply