because leaving the with-block calls the object's __exit__() function https://peps.python.org/pep-0343/ which for a filehandle is equivalent to a close() https://docs.python.org/3/reference/datamodel.html#object.__exit__ so after you jump out of the with-block's indent, the file handle's close function has been called and it's no longer readable Answer from eruciform on reddit.com
🌐
Python
docs.python.org › 3 › library › csv.html
csv — CSV File Reading and Writing
The csv module’s reader and writer objects read and write sequences. Programmers can also read and write data in dictionary form using the DictReader and DictWriter classes. ... The Python Enhancement Proposal which proposed this addition to Python.
🌐
University of Washington
courses.cs.washington.edu › courses › cse160 › 22au › computing › csv-parsing.html
How to parse csv formatted files using csv.DictReader
import csv people_csv = open("people.csv") input_file = csv.DictReader(people_csv) max_age = None oldest_person = None for row in input_file: age = int(row["age"]) if max_age is None or max_age < age: max_age = age oldest_person = row["name"] people_csv.close() if max_age is not None: print("The oldest person is", oldest_person, "who is", max_age, "years old.") else: print("The file does not contain any people.")
🌐
Medium
medium.com › @3valuedlogic › using-python-csv-3-dictreader-e4814ce2e44
Using Python CSV #3 — DictReader
December 22, 2022 - Our fieldnames should be the first row (the header): ‘name’, ‘age’, and ‘account’. These should map to the name, age, and account size of each person. Let’s check by printing out each dictionary. We can do this by printing each item in the DictReader object:
🌐
Reddit
reddit.com › r/learnpython › when using reader or dictreader from the csv module, why do you need to access the return value while the file is still open?
r/learnpython on Reddit: When using reader or DictReader from the csv module, why do you need to access the return value while the file is still open?
August 7, 2023 -

Ok, this will make more sense. Why does this work:

import csv

with open('test.csv') as csv_file:
    csv_reader = csv.DictReader(csv_file)
    for row in csv_reader:
        print(row)

But this gives an error that the file is closed:

import csv

with open('test.csv') as csv_file:
    csv_reader = csv.DictReader(csv_file)

for row in csv_reader:
    print(row)

Traceback (most recent call last):
File "c:\Users\John\Documents\Python\test_project\test2.py", line 5, in <module> for row in csv_reader: File "C:\Users\John\AppData\Local\Programs\Python\Python311\Lib\csv.py", line 110, in next self.fieldnames File "C:\Users\John\AppData\Local\Programs\Python\Python311\Lib\csv.py", line 97, in fieldnames self._fieldnames = next(self.reader) ^ 
ValueError: I/O operation on closed file.

Does DictReader (and also reader) not just run once and return a value? Why is csv_file being accessed after the line it's used in?

Thanks!

🌐
Veerpal Brar
veerpalbrar.github.io › blog › 2016 › 08 › 05 › Reading-CSV-Files-with-Python
Reading CSV files with Python
August 5, 2016 - Both read the file row by row and ... where each element is a data value from the row. The DictReader returns a dictionary where the column headings are the keys, and the values are the data values of the row....
Find elsewhere
🌐
Brodan
brodan.biz › blog › parsing-csv-files-with-python
Parsing CSV Files with Python's DictReader
August 24, 2018 - The DictReader class basically creates a CSV object that behaves like a Python OrderedDict. It works by reading in the first line of the CSV and using each comma separated value in this line as a dictionary key.
🌐
GeeksforGeeks
geeksforgeeks.org › python › working-csv-files-python
Working with csv files in Python - GeeksforGeeks
We can read a CSV file into a dictionary using the csv module in Python and the csv.DictReader class.
Published   August 5, 2025
🌐
GitHub
gist.github.com › j2labs › 5892515
Example of using Python's csv module with DictReader · GitHub
Example of using Python's csv module with DictReader · Raw · gistfile1.py · 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.
🌐
Bowmanjd
bowmanjd.com › python-csv-dictreader
Flexible CSV Handling in Python with DictReader and DictWriter | Jonathan Bowman
September 21, 2020 - inpath = Path("sample.csv") outpath = Path("out/transformed.csv") args = {"newline": "", "encoding": "utf-8-sig"} with inpath.open("r", **args) as infile, outpath.open("w", **args) as outfile: reader = csv.DictReader(infile) writer = csv.DictWriter(outfile, ["Firstname", "Lastname", "Username"]) As you may already be aware, it is possible to pass a dictionary of keyword arguments to a Python function.
🌐
Python Beginners
python-adv-web-apps.readthedocs.io › en › latest › csv.html
CSV Files — Python Beginners documentation
The code above will print 46 lines, ... a for-loop to read from all rows in the CSV. Close the file. The csv.DictReader() method is used to convert a CSV file to a Python dictionary....
🌐
Imperial College London
python.pages.doc.ic.ac.uk › java › lessons › java › 10-files › 09-csvreaddict.html
Python for Java Programmers > Reading CSV files into a dict | Department of Computing | Imperial College London
To make life easier, you can also read in the CSV files into a dict, using a csv.DictReader object. You can then access elements using the column names as keys (from the first row).
🌐
Python Pool
pythonpool.com › home › blog › csv dicteader doesn’t have to be hard
CSV Dicteader Doesn't Have To Be Hard - Python Pool
December 18, 2021 - In this article we have learned about python csv DictReader class. We used reading a CSV file and then perform the operations on them.
🌐
DEV Community
dev.to › thumbone › dumping-data-with-pythons-csv-dictwriter-1g0
Dumping Data with Python's CSV DictWriter - DEV Community
May 16, 2025 - The DictWriter lets you write CSV files very neatly and semantically by defining each row as a Python dict.
🌐
W3Schools
w3schools.com › python › ref_module_csv.asp
Python csv Module
Python Examples Python Compiler ... for row in r: print(row) Try it Yourself » · The csv module reads and writes tabular data in CSV (Comma Separated Values) format....
🌐
DaniWeb
daniweb.com › programming › software-development › threads › 184037 › csv-dictreader-problems
python - CSV.DictReader Problems | DaniWeb
March 29, 2009 - It is an iterator that yields one dict per row; you do not delete keys from the reader, you operate on the dicts it produces. Also, notice your keys have leading spaces (e.g. ' ExeShares').
🌐
GitHub
github.com › MLH-Fellowship › PE-Hackathon-Template-2026
GitHub - MLH-Fellowship/PE-Hackathon-Template-2026 · GitHub
April 3, 2026 - import csv from peewee import chunked from app.database import db from app.models.product import Product def load_csv(filepath): with open(filepath, newline="") as f: reader = csv.DictReader(f) rows = list(reader) with db.atomic(): for batch in chunked(rows, 100): Product.insert_many(batch).execute() from peewee import fn from playhouse.shortcuts import model_to_dict # Select all products = Product.select() # Filter cheap = Product.select().where(Product.price < 10) # Get by ID p = Product.get_by_id(1) # Create Product.create(name="Widget", category="Tools", price=9.99, stock=50) # Convert to
Starred by 19 users
Forked by 55 users
Languages   Python