You are currently viewing Python: How to Read CSV Files

Python: How to Read CSV Files

Working with CSV files is a common task in data analysis and manipulation. CSV (comma-separated values) files are plain text files that store tabular data in a structured format. Python provides a built-in csv module that makes it easy to read and write CSV files.

The example program reads a CSV file and prints its headers and rows. It’s assumed that the headers are the first row in the file, so if the file has no headers, you should set the exclude_headers parameter to False when calling the rows method of the CSVFileReader class:

import csv


class CSVFileReader:

    def __init__(self, file_path, delimiter=',', dialect='excel', **kwargs):

        with open(file_path, 'r') as file:
            self.reader = csv.reader(file, delimiter=delimiter, dialect=dialect, **kwargs)
            self.records = [record for record in self.reader if len(record) > 0]

    def rows(self, exclude_headers=True):
        return self.records[1:] if exclude_headers else self.records

    def headers(self):
        return self.records[0]


if __name__ == '__main__':

    filename = 'demo.csv'

    try:

        reader = CSVFileReader(filename)

        print(reader.headers())

        for row in reader.rows():
            print(row)

    except FileNotFoundError:
        print(f"{filename} not found.")

    except csv.Error as e:
        print(f"Error while reading {filename}: {e}")

For those interested in understanding how to create and write data to CSV files using Python, please refer to my other article on this topic titled Working with CSV Files in Python: Writing.

I sincerely hope that you find this code helpful. If you wish to learn more about Python, please subscribe to our newsletter today and continue your Python learning journey with us!

Leave a Reply