Created
August 5, 2025 09:45
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
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