I want to simplify the repetitive work of creating a DictWriter in a with context manager.

So I created a @contextmanager decorated DictWriter, and yielded that, to use in my code. Is this correct?

This seems to work, but yielding from within a with seems redundant.

#!/usr/bin/env python
import csv
import pathlib
from contextlib import contextmanager

def dict_writer(path, headers):
    with open(path, 'w', newline='', encoding='utf-8') as f:
        writer = csv.DictWriter(f, fieldnames=headers, extrasaction='ignore')
        yield writer

def main():
    path = pathlib.Path('~/Desktop/test.csv').expanduser()
    headers = ['site', 'user']
    with dict_writer(path, headers) as writer:
        writer.writerow({'site': 1, 'user': 'foo'})  # Works
    writer.writerow({})  # Causes: ValueError: I/O operation on closed file.

if __name__ == '__main__':
  • 1
    \$\begingroup\$ Please post your test cases so that we might help you to augment them. \$\endgroup\$
    – pacmaninbw
    Apr 8, 2022 at 18:18
  • 2
    \$\begingroup\$ @pacmaninbw the main() function is the test case. As I said, it currently appears to work as expected. \$\endgroup\$
    – supermitch
    Apr 8, 2022 at 18:37


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Browse other questions tagged or ask your own question.