๐ How to Read a CSV File in Python
Reading CSV files is one of the most common tasks in Python. The built-in csv module and pandas both make it simple.
Always use encoding='utf-8' in open() if your CSV has special characters or emojis.
๐ป Code Example:
import csv # Reading with built-in csv module with open('pynfinity_data.csv', 'r') as file: reader = csv.DictReader(file) for row in reader: print(row['name'], row['score']) # Reading with pandas (recommended for data work) import pandas as pd df = pd.read_csv('pynfinity_data.csv') print(df.head()) print(df.shape) # (rows, columns)
| Concept | Key Takeaway |
|---|---|
| csv.reader | Reads rows as lists โ good for simple files |
| csv.DictReader | Reads rows as dicts โ best for named columns |
| pd.read_csv() | Most powerful โ handles encoding, separators, and large files |
| df.head(n) | Preview first n rows quickly |
Keep exploring and happy coding! ๐