Learning

CSV File Operations

CSV File Operations

Reading CSV Files

python
import csv # Method 1: csv.reader (returns lists) with open('data.csv', 'r', newline='') as f: reader = csv.reader(f) header = next(reader) # Skip header row for row in reader: print(row) # ['Alice', '25', 'NYC'] # Method 2: csv.DictReader (returns dicts — BETTER!) with open('data.csv', 'r', newline='') as f: reader = csv.DictReader(f) for row in reader: # row is OrderedDict or dict print(row['Name'], row['Age']) # Access all fieldnames with open('data.csv', 'r') as f: reader = csv.DictReader(f) print(reader.fieldnames) # ['Name', 'Age', 'City']

Important: Always use newline='' when opening files for the csv module to prevent double newlines on Windows.

Writing CSV Files

python
import csv # Method 1: csv.writer (from lists) data = [ ['Name', 'Age', 'City'], ['Alice', 25, 'NYC'], ['Bob', 30, 'LA'] ] with open('output.csv', 'w', newline='') as f: writer = csv.writer(f) writer.writerows(data) # Write multiple rows # writer.writerow(['Charlie', 22, 'CHI']) # Write single row # Method 2: csv.DictWriter (from dicts — BETTER!) fields = ['Name', 'Age', 'City'] data = [ {'Name': 'Alice', 'Age': 25, 'City': 'NYC'}, {'Name': 'Bob', 'Age': 30, 'City': 'LA'} ] with open('output.csv', 'w', newline='') as f: writer = csv.DictWriter(f, fieldnames=fields) writer.writeheader() # Write the header row writer.writerows(data) # Write all data rows

Handling Special Cases

python
# Custom delimiter (e.g., TSV - tab separated) with open('data.tsv', 'r') as f: reader = csv.reader(f, delimiter='\t') for row in reader: print(row) # Quoting (handling commas inside values) with open('output.csv', 'w', newline='') as f: # csv.QUOTE_ALL, csv.QUOTE_MINIMAL (default), csv.QUOTE_NONNUMERIC writer = csv.writer(f, quoting=csv.QUOTE_ALL) writer.writerow(['Hello, World', 42]) # Output: "Hello, World","42" # Skipping bad rows with open('data.csv', 'r') as f: reader = csv.reader(f) for row in reader: if len(row) < 3: continue # Skip malformed rows process(row)
Key Rules
  • •Always use `newline=''` in the open() call when working with csv to avoid extra blank lines
  • •DictReader is almost always better than reader — it gives you named columns instead of indices
  • •DictWriter requires explicit fieldnames and you MUST call writeheader() to write the column names
  • •Use delimiter='\t' for TSV files instead of the default comma
  • •csv.writer handles quoting automatically — you don't need to manually escape commas inside values
Your Task

Create a function `read_employees(filepath)` that reads a CSV with columns 'Name', 'Department', 'Salary' and returns a list of dictionaries. Create a function `write_employees(filepath, employees)` that writes the list of dicts back to CSV, but add a new column 'Tax' which is 10% of Salary (round to 2 decimals). Use DictReader and DictWriter.

EditorPython · JSX
PreviewUpdates on Run Tests
Loading preview…
Tests
Should import csv module
Should use csv.DictReader
Should define read_employees function
Should define write_employees function
Should use csv.DictWriter
Should call writeheader()