其他分享
首页 > 其他分享> > csv文件操作封装

csv文件操作封装

作者:互联网

csv库常用封装


import csv


def csv_write_dict(path, fieldnames, dic_row_list):
      """
      字典形式写入csv文件
      :param fieldnames: []
      :param dic_row_list: [{},{}]
      :return:
      """
      with open(path, 'w', newline='') as csvfile:
            # 构建字段名称,key
            writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
            # 写入字段名作表头
            writer.writeheader()
            # 多行写入
            writer.writerows(dic_row_list)
def csv_write_rows(self, row_list):
    """
    多行写入
    :param row_list: [[],[],[]]
    :return:
    """
    # 按行写入
    with open(self.path, 'wb') as f:
        f.write(codecs.BOM_UTF8)  # 防止输出为乱码
        f_csv = csv.writer(f)
        f_csv.writerows(row_list)
def csv_read_dict(path):
      # 以列表形式,读取csv文件
      path = r'E:\huangrong\code\python\TestEnvironmentalGovernance\file\data.log'
      with open(path, 'r') as f:
          r_csv = csv.reader(f)
          li = [row for row in r_csv]
          print(li)
          return li




if __name__ == '__main__':
      path = r'E:\huangrong\code\learning\code\ApiTest\file\test.csv'
      fieldnames = ['first_name', 'last_name']
      dic_row_list = [{'first_name': 'Baked', 'last_name': 'Beans'}, {'first_name': 'Lovely', 'last_name': 'Spam'}]
      # csv_write_dict(path, fieldnames, dic_row_list)
      csv_read_dict(path)

标签:文件,封装,name,list,fieldnames,path,csv,row
来源: https://blog.csdn.net/lanniya152/article/details/122160622