• Python+pandas编写命令行脚本操作excel的小tips



    一、前言

    这里用了我的日志小工具 https://blog.csdn.net/weixin_43721000/article/details/123427891
    如果不想用这个,可以把日志输出的代码换成 print() 或者删掉


    二、tips

    1.使用说明格式

    # 使用说明 -----------------------------------
    time.sleep(1)
    print('===========================================================')
    print('简单说明:使用正则表达式拆分excel表中不规范的作者,初步提取对应需求字段')
    print('PS:')
    print('1.文件夹下需要有一个excel(只放一个,名称随意),其中一列“作者”保存着待拆分的作者')
    print('2.拆分后的excel将新增几列拆分结果列,以 <作者>[拆分] 作为列名标记')
    print('===========================================================')
    time.sleep(1)
    # ------------------------------------------
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    2.接收操作目录方法

    # 输入操作路径 ----------------------------------------------------------------
    operate_dir = input('请输入excel目录(旺柴):')  # D:\PycharmProjects\spiders\图片下载工具\excel
    operate_dir = os.path.abspath(operate_dir)
    # operate_dir = os.path.abspath(r'C:\Users\cxstar46\Desktop\正则表达式题名拆分测试')
    # -----------------------------------------------------------------------------
    
    • 1
    • 2
    • 3
    • 4
    • 5

    3.检测并读取目录下的excel,并限制当前目录只能放一个excel

    # 检测excel数量,只能放一个,当只有一个excel时,提取它的路径excel_path -------
    log.info('检查路径下的文件格式...')
    excel_name = None
    excel_count = 0
    file_list = os.listdir(operate_dir)
    for file in file_list:
        if file.endswith('.xlsx') or file.endswith('.xlx'):
            excel_count += 1
            excel_name = file
    if excel_count == 0:
        log.error('文件夹下没有excel')
        input('按任意键退出...')
        raise Exception(0)
    if excel_count > 1:
        log.error("无法读取excel,文件夹下有多个excel,或者excel未关闭")
        input('按任意键退出...')
        raise Exception(0)
    
    # print(excel_name)
    # raise Exception(1212)
    # ----------------------------------------------------------------------
    # print(excel_path)
    # print(img_dir)
    
    # 读取excel ----------------------------------------
    excel_path = os.path.join(operate_dir, excel_name)
    # print(excel_path)
    try:
        df = pd.read_excel(excel_path)
        df = df.where(df.notnull(), None)
    except Exception as e:
        log.error(e)
        log.error('文件不存在或已损坏...')
        input('按任意键退出...')
        raise Exception(0)
    # -------------------------------------------------
    
    # 打印excel行数
    print(df.shape[0])
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39

    4.备份excel

    # 备份原始excel表 --------------------------------------------------------------
    log.info('备份excel...')
    bak_dir = '封面上传前的备份'   # 备份文件夹的名称
    file_list = os.listdir(operate_dir)
    if bak_dir not in file_list:
        os.makedirs(os.path.join(operate_dir, bak_dir))
    bak_excel_path = os.path.join(os.path.join(operate_dir, bak_dir), "{}_{}".format(datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S"), excel_name))
    shutil.copyfile(excel_path, bak_excel_path)
    # -----------------------------------------------------------------------------
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    5.报错暂停,并显示异常信息

    try:
    
        raise Exception("执行业务报错")
    
    except Exception as e:
        import traceback
        log.error(traceback.format_exc())	# 记录异常信息
    
    input('执行完毕,按任意键继续...')
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    6.判断excel是否包含某列,不包含就新建

    cover_ruid_col_name = "封面ruid"
    
    # 没有封面ruid这一列就创建
    if cover_ruid_col_name not in df.columns.values:
        df.loc[:, cover_ruid_col_name] = None
    
    • 1
    • 2
    • 3
    • 4
    • 5

    7.进度展示与阶段保存

    # 读取excel
    excel_path = './封面上传测试.xlsx'
    df = pd.read_excel(excel_path)
    
    
    review_col = "审核结果"
    # 没有“审核结果”这一列就创建
    if review_col not in df.columns.values:
        df.loc[:, review_col] = None
    
    
    for i in range(df.shape[0]):
    	
    	# 打印进度 ---------------------------------------------
        log.info("----------------------------------")
        log.info("当前进度: {} / {}".format(i+1, df.shape[0]))
        # ----------------------------------------------------
    	
    	# 执行表格插入业务
    	# 判断业务
    	# 吧啦吧啦
    	# 业务执行结果插入原表
    	df.loc[i, "审核结果"] = "好耶"
    	
        # 阶段性保存 ----------------------------
        save_space = 200	# 每执行两百行保存一次
        if i+1 % save_space == 0 and i != 0:
            df.to_excel(excel_path, index=0)
            log.info("阶段性保存...")
        # -------------------------------------
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30

  • 相关阅读:
    宏集案例 | eX707G人机界面在石油钻井工程中的应用
    指令的类型
    Java集合框架之Map集合
    数据结构:AVLTree的插入和删除的实现
    KMP算法——通俗易懂讲好KMP算法:实例图解分析+详细代码注解 --》你的所有疑惑在本文都能得到解答
    C语言 数据在内存中的存储
    python 基于aiohttp的异步爬虫实战
    校园wifi网页认证登录入口
    传言称 iPhone 16 Pro 将支持 40W 快速充电和 20W MagSafe
    曲柄压力机的离合器和制动系统设计
  • 原文地址:https://blog.csdn.net/weixin_43721000/article/details/126016051