文件读写器操作通过open()函数进行操作,使用带关键字读写器文件就不用再惦记着要关闭文件时。 首先来看一个简单的常规文件读写操作;f = open('test.txt', mode='w+', encoding='utf-8')f.write(','.join([t for t in range(1000)]))f.close()f = open('test.txt', mode='r', encoding='utf-8')print(f.read())f.close() 再看一个省心的文件读写操作
Excel操作Excel文件操作常用的库有xlrd、xlwt、openpyxl、xlswriter已经pandas等;
# 设置表格样式def set_style(name, height, bold=False): style = xlwt.XFStyle() font = xlwt.Font() font.name = name font.bold = bold font.color_index = 4 font.height = height style.font = font return styledef write_excel(file_name: str, info: List, table_head: Optional[List], sheet: str = 'data', save_path: str = '', *args, **kwargs) -> str: ''' xlwt库创建Excel ''' try: file_name += '.xls' save_file = os.path.join(save_path, file_name) if save_path else file_name # Excel文件保存路径 workbook = xlwt.Workbook() # 创建Excel sheet1 = workbook.add_sheet(sheet, cell_overwrite_ok=True) # 增加sheet页 for i in range(0, len(table_head)): # 写表头数据 sheet1.write(0, i, table_head[i], set_style('Times New Roman', 220, True)) for i in range(len(info)): # 从第二行开始写数据 item = info[i] for j in range(len(table_head)): field = table_head[j] sheet1.write(i + 1, j, item[field], set_style('Times New Roman', 220, True)) workbook.save(save_file) logger.info(f'Excel文件: {file_name}, 保存成功') return save_file except Exception as e: logger.exception(f'Excel文件处理异常: {str(e)}') return ''
def write_excel_xlsx(file_name: str, info: List, table_head: Optional[List], sheet: str = 'data', save_path: str = ''): ''' 数据写入Excel,导出Excel文件, 支持xlsx类型 使用xlsxwriter库 :param file_name: excel文件名称 :param info: 写入的数据 :param table_head: 数据表头 :param sheet: sheet页名称 :param save_path: 保存路径 :return: ''' try: down_path = os.path.expanduser('~') # 用户目录 file_name += '.xlsx' down_path_file = os.path.join(save_path, file_name) if save_path else \ os.path.join(down_path, file_name) # excel文件地址 workbook = xlsxwriter.Workbook(down_path_file) # 创建Excel文件 worksheet = workbook.add_worksheet(sheet) # 创建sheet,名为data format1 = workbook.add_format( {'bold': True, 'font_color': 'black', 'font_size': 13, 'align': 'left', 'font_name': u'宋体'}) # 表头格式 format2 = workbook.add_format({'font_color': 'black', 'font_size': 11, 'align': 'left', 'font_name': u'宋体'}) # 表头外格式 worksheet.set_column('A:A', 10) # A列列宽设置能更好的显示 for i in range(0, len(table_head)): # 插入第一行表头标题 field = table_head[i] worksheet.write(0, i, field, format1) # 从第二行开始插入数据 for i in range(len(info)): item = info[i] # 行数据 for j in range(len(table_head)): field = table_head[j] worksheet.write(i + 1, j, item[field], format2) workbook.close() alert_text = '导出成功,导出地址:{}!'.format(down_path_file) return down_path_file except Exception as e: logger.exception('导出Excel异常: {}'.format(e)) return ''
def openpyxl_read_excel(file_name: str, sheet_name: str = '', sheet_index: int = 0, data_type: int = 0) -> List: ''' 读取Excel文件 使用openpyxl库 param data_type: 列表中数据类型 0:list, 1: dict ''' workbook = load_workbook(file_name) # 加载Excel文件 # booksheet = workbook.active # 获取当前活跃的sheet,默认是第一个sheet # 如果想获取别的sheet页采取下面这种方式,先获取所有sheet页名,在通过指定那一页。 sheets = workbook.sheetnames # workbook.get_sheet_names() # 从名称获取sheet # booksheet = workbook.get_sheet_by_name(sheet_name) try: booksheet = workbook[sheet_name] if sheet_name else workbook[sheets[sheet_index]] except Exception as e: booksheet = workbook[sheets[0]] rows = booksheet.rows # 获取sheet页的行数据 columns = booksheet.columns # 获取sheet页的列数据 li = [] table_head = [] for idx, row in enumerate(rows): # 迭代所有的行 line = [col.value for col in row] if idx == 0: table_head.extend(line) # 列表数据追加到列表 continue if data_type == 0: li.append(line) # 数据形式为列表 else: di = dict(zip(table_head, line)) # 数据转换为字典 li.append(di) return li
根据以上库的使用,可以看出openpyxl和pandas的功能更加坚固和强大,尤其是pandas,对于数据操作来说那简直方便的飞起! 以下是各个库的性能对比,该图是从知乎网上得来的,凡事有删减! ![]() |
|
来自: 网摘文苑 > 《office与VBA》