Python+pandas編寫命令行腳本操作excel的tips詳情
更新時間:2022年07月28日 16:05:45 作者:什么都干的派森
這篇文章主要介紹了Python+pandas編寫命令行腳本操作excel的tips詳情,文章圍繞主題展開詳細的內容介紹,具有一定的參考價值,需要的朋友可以參考一下
一、python logging日志模塊簡單封裝
項目根目錄創(chuàng)建 utils/logUtil.py
import logging from logging.handlers import TimedRotatingFileHandler from logging.handlers import RotatingFileHandler class Log(object): STAND = "stand" # 輸出到控制臺 FILE = "file" # 輸出到文件 ALL = "all" # 輸出到控制臺和文件 def __init__(self, mode=STAND): self.LOG_FORMAT = "%(asctime)s - %(levelname)s - %(message)s" self.logger = logging.getLogger() self.init(mode) def debug(self, msg): self.logger.debug(msg) def info(self, msg): self.logger.info(msg) def warning(self, msg): self.logger.warning(msg) def error(self, msg): self.logger.error(msg) def init(self, mode): self.logger.setLevel(logging.DEBUG) if mode == "stand": # 輸出到控制臺 ------ self.stand_mode() elif mode == "file": # 輸出到文件 -------- self.file_mode() elif mode == "all": # 輸出到控制臺和文件 self.stand_mode() self.file_mode() def stand_mode(self): stand_handler = logging.StreamHandler() stand_handler.setLevel(logging.DEBUG) stand_handler.setFormatter(logging.Formatter(self.LOG_FORMAT)) self.logger.addHandler(stand_handler) def file_mode(self): ''' filename:日志文件名的prefix; when:是一個字符串,用于描述滾動周期的基本單位,字符串的值及意義如下: “S”: Seconds “M”: Minutes “H”: Hours “D”: Days “W”: Week day (0=Monday) “midnight”: Roll over at midnight interval: 滾動周期,單位有when指定,比如:when='D',interval=1,表示每天產(chǎn)生一個日志文件; backupCount: 表示日志文件的保留個數(shù); ''' # 輸出到文件 ----------------------------------------------------------- # 按文件大小輸出 # file_handler = RotatingFileHandler(filename="my1.log", mode='a', maxBytes=1024 * 1024 * 5, backupCount=10, encoding='utf-8') # 使用RotatingFileHandler類,滾動備份日志 # 按時間輸出 file_handler = TimedRotatingFileHandler(filename="my.log", when="D", interval=1, backupCount=10, encoding='utf-8') file_handler.setLevel(logging.DEBUG) file_handler.setFormatter(logging.Formatter(self.LOG_FORMAT)) self.logger.addHandler(file_handler) log = Log(mode=Log.STAND)
使用方法:
from utils.logUtil import log if __name__ == '__main__': log.debug("debug msg") log.info("info msg") log.warning("warning msg") log.error("error msg")
跑一下測試結果:
二、pandas編寫命令行腳本操作excel的小tips
這里用上面日志小工具
如果不想用這個,可以把日志輸出的代碼換成 print() 或者刪掉
1、tips
1.1使用說明格式
# 使用說明 ----------------------------------- time.sleep(1) print('===========================================================') print('簡單說明:使用正則表達式拆分excel表中不規(guī)范的作者,初步提取對應需求字段') print('PS:') print('1.文件夾下需要有一個excel(只放一個,名稱隨意),其中一列“作者”保存著待拆分的作者') print('2.拆分后的excel將新增幾列拆分結果列,以 <作者>[拆分] 作為列名標記') print('===========================================================') time.sleep(1) # ------------------------------------------
1.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.3檢測并讀取目錄下的excel,并限制當前目錄只能放一個excel
# 檢測excel數(shù)量,只能放一個,當只有一個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行數(shù) print(df.shape[0])
1.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.5報錯暫停,并顯示異常信息
try: raise Exception("執(zhí)行業(yè)務報錯") except Exception as e: import traceback log.error(traceback.format_exc()) # 記錄異常信息 input('執(zhí)行完畢,按任意鍵繼續(xù)...')
1.6判斷excel是否包含某列,不包含就新建
cover_ruid_col_name = "封面ruid" # 沒有封面ruid這一列就創(chuàng)建 if cover_ruid_col_name not in df.columns.values: df.loc[:, cover_ruid_col_name] = None
1.7進度展示與階段保存
# 讀取excel excel_path = './封面上傳測試.xlsx' df = pd.read_excel(excel_path) review_col = "審核結果" # 沒有“審核結果”這一列就創(chuàng)建 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])) # ---------------------------------------------------- # 執(zhí)行表格插入業(yè)務 # 判斷業(yè)務 # 吧啦吧啦 # 業(yè)務執(zhí)行結果插入原表 df.loc[i, "審核結果"] = "好耶" # 階段性保存 ---------------------------- save_space = 200 # 每執(zhí)行兩百行保存一次 if i+1 % save_space == 0 and i != 0: df.to_excel(excel_path, index=0) log.info("階段性保存...") # -------------------------------------
到此這篇關于Python+pandas編寫命令行腳本操作excel的tips詳情的文章就介紹到這了,更多相關Python操作excel的tips內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
您可能感興趣的文章:
- Python Pandas pandas.read_sql_query函數(shù)實例用法分析
- python中pandas操作apply返回多列的實現(xiàn)
- python?pandas創(chuàng)建多層索引MultiIndex的6種方式
- Python Pandas實現(xiàn)DataFrame合并的圖文教程
- Python的Django框架實現(xiàn)數(shù)據(jù)庫查詢(不返回QuerySet的方法)
- Python中類似于jquery的pyquery庫用法分析
- python實現(xiàn)合并多個list及合并多個django QuerySet的方法示例
- python?pandas?query的使用方法
相關文章
淺談python str.format與制表符\t關于中文對齊的細節(jié)問題
今天小編就為大家分享一篇淺談python str.format與制表符\t關于中文對齊的細節(jié)問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-01-01Python中tkinter開發(fā)的常用29種功能用法總結
tkinter(Tk?interface)是Python的標準GUl庫,支持跨平臺的GUl程序開發(fā),本文為大家整理了tkinter開發(fā)時常用的29種功能用法,希望對大家有所幫助2023-05-05