每次都必须在 csv 中打开 DictWriter 来减少代码重复?

问题描述 投票:0回答:1

我想通过每次需要写入 csv 文件时都必须使用 DictWriter 创建一个变量以及所有他的信息来减少代码重复。

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

            ...

我想使用 open 函数创建一个私有类属性来传递文件,比如

_csv_writer = DictWriter(open('filepath'))
不需要每次都创建一个 DictWriter,但是如果我这样做,文件将不会像 with 中那样关闭 经理对吗?那么还有其他选择来减少该代码并仍然关闭文件吗?

python csv
1个回答
0
投票

您无法轻松避免

open()
调用,因为它们位于上下文管理器中(除非您想定义自己的上下文管理器),但您可以定义一个使用您的选项调用
DictWriter()
的函数,这样您就不需要不必重复。

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)

© www.soinside.com 2019 - 2024. All rights reserved.