Python Tutorial: Writing Python Data Class to CSV!

Python Tutorial: Writing Python Data Class to CSV!

ยท

2 min read

Objective:

Learn how to convert a Python data class to a CSV (Comma-Separated Values) file.

Step 1:

Import Necessary Modules

import csv
from dataclasses import dataclass

Step 2:

Define a Data Class Create a data class representing the data structure you want to convert to CSV.

@dataclass
class Person:
    name: str
    age: int
    city: str

Step 3:

Create Data Instances Instantiate objects of the data class to represent individual records.

person1 = Person("Alice", 25, "New York")
person2 = Person("Bob", 30, "San Francisco")
person3 = Person("Charlie", 22, "Los Angeles")

Step 4:

Convert Data Class Instances to CSV Define a function to convert data class instances to CSV and write to a file.

def write_to_csv(file_path, data_instances):
    with open(file_path, mode='w', newline='') as file:
        writer = csv.writer(file)

        # Write header
        writer.writerow(data_instances[0].__annotations__.keys())

        # Write data
        for instance in data_instances:
            writer.writerow(instance.__dict__.values())

Step 5: Call the Function Call the function with the file path and the list of data class instances.

data_instances = [person1, person2, person3]
write_to_csv('people.csv', data_instances)

Step 6:

Check the Output Inspect the generated CSV file (people.csv) to verify that the data has been successfully written.

Conclusion:

This tutorial provides a basic overview of converting Python data class instances to a CSV file. As you progress, you can explore additional features of the csv module and enhance the code to handle more complex scenarios. This foundational knowledge will be beneficial as you delve further into Python programming.

I hope this helps, you!!

More such articles:

https://medium.com/techwasti

https://www.youtube.com/@maheshwarligade

https://techwasti.com/series/spring-boot-tutorials

https://techwasti.com/series/go-language

Did you find this article valuable?

Support techwasti by becoming a sponsor. Any amount is appreciated!

ย