In this tutorial, we are going to explore how to convert Python List of objects to CSV file.

Convert Python List Of Objects to CSV:

As part of this example, I am going to create a List of Item objects and export/write them into CSV file using the csv package.

Recommended: How to read data from CSV file in Python

Convert List Of Objects to CSV:

  • Creating an Item class.
  • Prepare a list of Item objects
  • Create items.csv file
  • write Items data into items.csv file
list_to_csv.py
import csv

class Items(object):

    def __init__(self, id, name, category):
        self.__id = id
        self.__name = name
        self.__category = category
        self.__index = -1

    @property
    def id(self):
        return self.__id

    @property
    def name(self):
        return self.__name

    @property
    def category(self):
        return self.__category

if __name__ == '__main__':
    filename = 'items.csv'
    items = [Items(100, 'iPhone 10', 'Mobiles'), Items(200, 'Lenovo', 'Laptops')
        , Items(300, 'Java in Action', 'Books'), Items(400, 'Python', 'Books')]
    try:
        with open(filename, 'w') as f:
            writer = csv.writer(f)
            for item in items:
                writer.writerow([item.id, item.name, item.category])
    except BaseException as e:
        print('BaseException:', filename)
    else:
        print('Data has been loaded successfully !')

Code Walkthrough:

  • Created an Item class with id, name and category properties and created constructor.
  • Created a List of Item objects.
  • Open items.csv file with write permissions.
  • Iterating the Items list and write each item to the file.
  • Create CSV writer, writer.writerow() function used to write a complete row with the given parameters in a file.

Output:

Data has been loaded successfully !
items.csv
100,iPhone 10,Mobiles

200,Lenovo,Laptops

300,Java in Action,Books

400,Python,Books

References:

Happy Learning 🙂