Parse CSV Data with a Python Class
Encapsulate CSV file loading and column/row access methods in a reusable DataParser class for beginners.
Python code
37 linesclass DataParser:
def __init__(self, file_path):
self.file_path = file_path
self.data = []
def load_data(self):
with open(self.file_path, 'r') as file:
for line in file:
row = line.strip().split(',')
self.data.append(row)
return self.data
def get_column(self, column_index):
return [row[column_index] for row in self.data]
def get_row(self, row_index):
return self.data[row_index]
def row_count(self):
return len(self.data)
def column_count(self):
return len(self.data[0]) if self.data else 0
if __name__ == "__main__":
sample_data = "name,age,city\nAlice,25,New York\nBob,30,Los Angeles\nCharlie,35,Chicago"
with open('sample_data.csv', 'w') as f:
f.write(sample_data)
parser = DataParser('sample_data.csv')
parser.load_data()
print(f"Rows: {parser.row_count()}, Columns: {parser.column_count()}")
print(f"First row: {parser.get_row(0)}")
print(f"Names: {parser.get_column(0)}")
print(f"Ages: {parser.get_column(1)}")
Output
Rows: 3, Columns: 3
First row: ['name', 'age', 'city']
Names: ['name', 'Alice', 'Bob', 'Charlie']
Ages: ['age', '25', '30', '35']
How it works
The DataParser class uses an __init__ method to store the file path and initialize an empty list for data. The load_data method opens the file, strips each line, splits it by comma, and appends the resulting list to self.data. Methods like get_column and get_row provide easy access to parts of the data, while row_count and column_count return dimensions. This encapsulation promotes code reuse and readability, essential for OOP design.
Common mistakes
- Forgetting to handle empty files, causing `column_count` to return 0.
- Not stripping whitespace, leading to unexpected spaces in parsed values.
- Assuming the file exists without handling `FileNotFoundError`.
- Using `get_column` before calling `load_data`, resulting in an empty list.
Variations
- Use Python's built-in `csv` module for more robust parsing that handles quoted fields and different delimiters.
- Make the class accept a delimiter parameter to support TSV or other formats.
Real-world use cases
- Load configuration data from a local CSV file in a small automation script.
- Parse exported spreadsheet data for quick analysis in a data pipeline.
- Encapsulate file parsing logic to make unit testing easier in a larger application.
Sponsored
More from OOP & classes
- Add property getter setter validation in Python easy
- Binary Tree Inorder Traversal in Python easy
- Borg pattern shared state in Python medium
- Bridge Pattern in Python: Separate Abstraction from Implementation medium
- Composable Predicates with the &, |, ~ Operators in Python medium
- Composition over Inheritance: How to Build a Wallet Account in Python easy
Keep learning
Related tutorials and quizzes for this topic.