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
@contextmanager
def dict_writer(path, headers):
with open(path, 'w', newline='', encoding='utf-8') as f:
writer = csv.DictWriter(f, fieldnames=headers, extrasaction='ignore')
writer.writeheader()
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__':
main()
main()
function is the test case. As I said, it currently appears to work as expected. \$\endgroup\$