如何减少每次打开csv中的DictWriter导致的代码重复?

0 投票
2 回答
34 浏览
提问于 2025-04-14 17:32

我想减少代码重复,不想每次写入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管理器那样自动关闭,对吧?那有没有其他方法可以减少代码,同时又能确保文件关闭呢?

2 个回答

1

这两个函数之间唯一的区别就是在调用open()的时候,传入的参数是w还是a。所以,你只需要把这个参数传进去就可以了:

class Example:

    def func1(mode):
        with open('filepath', mode) as file:
            csv_writer = DictWriter(file, fieldnames=fieldnames, lineterminator='\n')

然后你可以根据需要调用func1('w')或者func1('a')

2

你不能轻易地避免使用 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)

撰写回答