当前位置: 代码迷 >> 综合 >> pyhton csv 二次封装
  详细解决方案

pyhton csv 二次封装

热度:96   发布时间:2024-02-24 07:10:17.0
# 导入内置的csv库文件
import csvclass CSVOPREATION(object):"""csv 文件操作"""def __init__(self, file_path):self.__csv_path = file_pathdef csv_write_list(self, data: list):"""写入列表格式的数据:param data: 列表格式的数据:return: None"""with open(self.__csv_path, "w", newline="", encoding="utf-8") as fp:csv_list_writer = csv.writer(fp)csv_list_writer.writerows(data)def csv_write_dict(self, data: list,  fieldnames: list):"""写入字典格式的数据:param data: 列表中中嵌套字典数据:param fieldnames: 列表格式的键:return: None"""with open(self.__csv_path, "w", newline="", encoding="utf-8") as fp:csv_dict_writer = csv.DictWriter(fp, fieldnames=fieldnames)  # fieldnames 表头csv_dict_writer.writeheader()csv_dict_writer.writerows(data)def reader_list(self):"""读取数据:输出列表:return: list"""with open(self.__csv_path, "r", encoding="utf-8") as fr:reader = csv.reader(fr)# 跳过第一行header = next(reader)# 遍历读取data_list = []for row in reader:data_list.extend(row)return header, data_listif __name__ == '__main__':# list_data = [['A', 'B', 'C', 'D'], ['A1', 'B1', 'C1', 'D1'], ['A2', 'B2', 'C2', 'D2']]# dict_data = [{"ID": 1, "NAME": "小敏", "AGE": 100},# {"ID": 2, "NAME": "小敏2", "AGE": 200},# {"ID": 3, "NAME": "小敏3", "AGE": 300}]# fieldnames = ["ID", "NAME", "AGE"]#csvopreation = CSVOPREATION("../data/cgmTest(0.2).csv")# 写入列表格式的数据# csvopreation.csv_write_list(list_data)# 写入字典格式的数据# csvopreation.csv_write_dict(dict_data, fieldnames)print(csvopreation.reader_list())# # 写入文件:数据源是列表
# with open("../data/csv_test1.csv", "w", newline="", encoding="utf-8") as fp:
# """
# newline 新的一行隔行去掉
# encoding 字符编码格式
# """
# list_data = [['A', 'B', 'C', 'D'], ['A1', 'B1', 'C1', 'D1'], ['A2', 'B2', 'C2', 'D2']]
# csv_list_writer = csv.writer(fp, dialect="excel")
#
# # 遍历写入
# # for row in list_data:
# # csv_list_writer.writerow(row)
#
# # 批量写入
# csv_list_writer.writerows(list_data)# # 写入文件:数据源是字典
# with open("../data/csv_test2.csv", "w", encoding="utf-8") as fp:
# fieldnames = ["ID", "NAME", "AGE"] # 字典中的键
# csv_dict_writer = csv.DictWriter(fp, fieldnames=fieldnames)
# # 先写入表头
# csv_dict_writer.writeheader()
# # 然后写入行数据
# dict_data = [{"ID": 1, "NAME": "小敏", "AGE": 100},
# {"ID": 2, "NAME": "小敏2", "AGE": 200},
# {"ID": 3, "NAME": "小敏3", "AGE": 300}]
#
# # 遍历写入
# # for row in dict_data:
# # csv_dict_writer.writerow(row)
#
# # 批量写入
# csv_dict_writer.writerows(dict_data)# # 读取数据:输出列表
# with open("../data/csv_test2.csv", "r", encoding="utf-8") as fr:
# # csv_reader = csv.reader(fr, delimiter=' ') # delimiter=' ' 修改读取出来数据的分隔符,默认是','
# csv_reader = csv.reader(fr)
# # 遍历读取
# for row in csv_reader:
# print(row)# # 读取数据:输出字典
# with open("../data/csv_test2.csv", "r", encoding="utf-8") as fr:
# fieldnames = ["ID", "NAME", "AGE"] # 字典中的键
# csv_reader = csv.DictReader(fr)
# # 遍历读取
# for i in list(csv_reader):
# print(dict(i))