Skip to content

Instantly share code, notes, and snippets.

@romuald
Created August 5, 2025 09:45
Show Gist options
  • Save romuald/4fee401620897b9556e19d6fb978e983 to your computer and use it in GitHub Desktop.
Save romuald/4fee401620897b9556e19d6fb978e983 to your computer and use it in GitHub Desktop.
A simple snippet that can be used to read CSV files with headers
"""
A simple snippet that can be used to read CSV files with headers
"""
import csv
from contextlib import contextmanager
@contextmanager
def dcsv(filename):
with open(filename) as reader:
dialect = csv.Sniffer().sniff(freader.read(8096))
freader.seek(0)
fields = csv.reader(reader, dialect).next()
yield csv.DictReader(reader, fields, dialect=dialect)
if __name__ == "__main__":
with dcsv("example.csv") as reader:
for line in reader:
print(line["id"], line["name"])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment