I want to reduce the code repetition by having to create a variable with a DictWriter and all he information every time I need to write in a csv file.
class Example:
def func1():
with open('filepath', 'w') as file:
csv_writer = DictWriter(file, fieldnames=fieldnames, lineterminator='\n')
...
def func2():
with open('filepath', 'a') as file:
csv_writer = DictWriter(file, fieldnames=fieldnames, lineterminator='\n')
...
I thinked in create a private class atribute using the open function to pass the file, like _csv_writer = DictWriter(open('filepath'))
to don’t need to create a DictWriter everytime, but if i do that the file will not close like in the with manager right? So have any other option to reduce that code and still closing the file?
>Solution :
You can’t easily avoid the open()
calls because they’re in a context manager (unless you want to define your own context manager), but you can define a function that calls DictWriter()
with your options so you don’t have to repeat them.
def myDictWriter(file):
return DictWriter(file, fieldnames=fieldnames, lineterminator='\n')
class Example:
def func1():
with open('filepath', 'w') as file:
csv_writer = myDictWriter(file)
...
def func2():
with open('filepath', 'w') as file:
csv_writer = myDictWriter(file)