代码之家  ›  专栏  ›  技术社区  ›  yFoxy _

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

  •  0
  • yFoxy _  · 技术社区  · 1 年前

    我想通过使用 DictWriter 以及每次我需要写csv文件时的所有信息。

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

    我想在创建一个私有类atribute时使用 打开 函数来传递文件,比如 _csv_writer = DictWriter(open('filepath')) 不需要每次都创建DictWriter,但如果我这样做,文件将不会像中那样关闭 具有 经理,对吧?那么,还有其他选择可以减少代码并关闭文件吗?

    1 回复  |  直到 1 年前
        1
  •  0
  •   Barmar    1 年前

    你无法轻易避免 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)
    
    
        2
  •  0
  •   John Gordon    1 年前

    这些功能之间的唯一区别是 w a 的论点 open() 。所以,把它作为一个论点:

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

    然后你会打电话 func1('w') func1('a') 根据需要。