Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I reduce code repetition by having to open a DictWriter in csv every time?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading