Python

How to Convert Python List Of Objects to CSV File

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 a 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', newline='') 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.
  • Iterate 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 :)

Found a mistake or something out of date? Tell us →

Written by

chandrashekhar

Founder of onlinetutorialspoint.com. Enterprise architect with 15+ years in healthcare technology, designing and running systems on AWS and Azure. Writes about building real things with AI, local AI hardware and cloud certifications.

Keep reading

2 comments

  1. Why is there a blank/empty row between the data?
    Is there a way to setup the writer and avoid that uneccesary row?

Ask a question or leave a comment