您好,登錄后才能下訂單哦!
本篇內(nèi)容主要講解“Python+pandas怎么編寫命令行腳本操作excel的tips”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實(shí)用性強(qiáng)。下面就讓小編來帶大家學(xué)習(xí)“Python+pandas怎么編寫命令行腳本操作excel的tips”吧!
項(xiàng)目根目錄創(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:是一個(gè)字符串,用于描述滾動(dòng)周期的基本單位,字符串的值及意義如下: “S”: Seconds “M”: Minutes “H”: Hours “D”: Days “W”: Week day (0=Monday) “midnight”: Roll over at midnight interval: 滾動(dòng)周期,單位有when指定,比如:when='D',interval=1,表示每天產(chǎn)生一個(gè)日志文件; backupCount: 表示日志文件的保留個(gè)數(shù); ''' # 輸出到文件 ----------------------------------------------------------- # 按文件大小輸出 # file_handler = RotatingFileHandler(filename="my1.log", mode='a', maxBytes=1024 * 1024 * 5, backupCount=10, encoding='utf-8') # 使用RotatingFileHandler類,滾動(dòng)備份日志 # 按時(shí)間輸出 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")
跑一下測試結(jié)果:
這里用上面日志小工具
如果不想用這個(gè),可以把日志輸出的代碼換成 print() 或者刪掉
# 使用說明 ----------------------------------- time.sleep(1) print('===========================================================') print('簡單說明:使用正則表達(dá)式拆分excel表中不規(guī)范的作者,初步提取對應(yīng)需求字段') print('PS:') print('1.文件夾下需要有一個(gè)excel(只放一個(gè),名稱隨意),其中一列“作者”保存著待拆分的作者') print('2.拆分后的excel將新增幾列拆分結(jié)果列,以 <作者>[拆分] 作為列名標(biāo)記') print('===========================================================') time.sleep(1) # ------------------------------------------
# 輸入操作路徑 ---------------------------------------------------------------- operate_dir = input('請輸入excel目錄(旺柴):') # D:\PycharmProjects\spiders\圖片下載工具\(yùn)excel operate_dir = os.path.abspath(operate_dir) # operate_dir = os.path.abspath(r'C:\Users\cxstar46\Desktop\正則表達(dá)式題名拆分測試') # -----------------------------------------------------------------------------
# 檢測excel數(shù)量,只能放一個(gè),當(dāng)只有一個(gè)excel時(shí),提取它的路徑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,文件夾下有多個(gè)excel,或者excel未關(guān)閉") 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])
# 備份原始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) # -----------------------------------------------------------------------------
try: raise Exception("執(zhí)行業(yè)務(wù)報(bào)錯(cuò)") except Exception as e: import traceback log.error(traceback.format_exc()) # 記錄異常信息 input('執(zhí)行完畢,按任意鍵繼續(xù)...')
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
# 讀取excel excel_path = './封面上傳測試.xlsx' df = pd.read_excel(excel_path) review_col = "審核結(jié)果" # 沒有“審核結(jié)果”這一列就創(chuàng)建 if review_col not in df.columns.values: df.loc[:, review_col] = None for i in range(df.shape[0]): # 打印進(jìn)度 --------------------------------------------- log.info("----------------------------------") log.info("當(dāng)前進(jìn)度: {} / {}".format(i+1, df.shape[0])) # ---------------------------------------------------- # 執(zhí)行表格插入業(yè)務(wù) # 判斷業(yè)務(wù) # 吧啦吧啦 # 業(yè)務(wù)執(zhí)行結(jié)果插入原表 df.loc[i, "審核結(jié)果"] = "好耶" # 階段性保存 ---------------------------- 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”有了更深的了解,不妨來實(shí)際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進(jìn)入相關(guān)頻道進(jìn)行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。