我想通过每次需要写入 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 中那样关闭 经理对吗?那么还有其他选择来减少该代码并仍然关闭文件吗?
您无法轻松避免
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)