Read a CSV File with csv.DictReader in Python
Read a CSV file as a list of dictionaries, using csv.DictReader to map each row to column names.
Python code
28 linesimport csv
from pathlib import Path
def read_csv_with_dictreader(file_path):
data = []
with open(file_path, mode='r', newline='', encoding='utf-8') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
data.append(row)
return data
if __name__ == "__main__":
# Create a sample CSV file for demonstration
sample_file = Path('sample.csv')
sample_file.write_text(
'name,age,city\n'
'Alice,30,New York\n'
'Bob,25,Los Angeles\n'
'Charlie,35,Chicago\n',
encoding='utf-8'
)
rows = read_csv_with_dictreader(sample_file)
for person in rows:
print(f"{person['name']} is {person['age']} years old and lives in {person['city']}.")
# Clean up sample file
sample_file.unlink()
Output
Alice is 30 years old and lives in New York.
Bob is 25 years old and lives in Los Angeles.
Charlie is 35 years old and lives in Chicago.
How it works
csv.DictReader reads each row as an OrderedDict, using the first row as keys. Opening the file with newline='' prevents platform-specific newline translation issues. The encoding='utf-8' parameter ensures Unicode safety. Each row is appended to a list as a dictionary, allowing easy access by column name. The context manager ensures the file closes automatically.
Common mistakes
- Forgetting `newline=''` when opening the file, which can cause extra blank lines.
- Assuming all rows have the same keys without checking for missing data.
- Not specifying `encoding='utf-8'`, leading to UnicodeDecodeError with non-ASCII characters.
Variations
- Use `with open(...) as f:` and `list(csv.DictReader(f))` for a one-liner.
- Read with `pandas.read_csv()` for built-in data analysis and transformation.
Real-world use cases
- Importing user records from an exported spreadsheet into a web app database.
- Reading batch configuration or metadata files in an ETL pipeline.
- Loading revenue or sales data from daily CSV dumps for reporting dashboards.
Sponsored
More from Files & data
- Append a Line to a Log File in Python easy
- Audit File Permissions Across a Project in Python easy
- Automatically Detect Corrupted Files Using SHA-256 Checksums in Python easy
- Automatically Highlight Data Validation Errors Inside Excel Files in Python easy
- Build a Command-Line To-Do List Application with Data Persistence in Python easy
- Build a File Index by Relative Path Hash Map in Python easy
Keep learning
Related tutorials and quizzes for this topic.