python 生成word目录

import win32com.client
import os
import time
import logging
from logging import handlers

def update_doc(file):
    word = win32com.client.DispatchEx("Word.Application")                                                               # 模拟打开 office
    try:
        doc = word.Documents.Open(file)                                                                                 # 打开文件
        doc.TablesOfContents(1).Update()                                                                                # 更新目录
        doc.Close(SaveChanges=True)                                                                                     # 关闭文档
        word.Quit()                                                                                                     # 退出
    except:
        print(file,"文件无目录!")

def run():
    #log = Logger(file_dir + '..\\Log\\' + 'codeDirLog.log', level='debug')
    #Logger('error.log', level='error').logger.error('error')
    #file = os.path.realpath('../Demo/') + '\\'                                                                         # 获取当前文件路径,并在尾部添加‘\’
    file=r'D:\Desktop\EJinDiao\static_file\上海国际机场股份有限公司'
    # file = os.path.realpath('')+'\\DataFileRes\\'                                                                                           # 获取当前文件路径,并在尾部添加‘\’
    files = os.listdir(file)                                                                                            # 获取当前路径下所有文件名称
    file_names = [f for f in files if f.endswith((".doc", ".docx"))]                                                    # 将所有word文件名称存入file_names
    print('待处理的文件列表:',file_names)
    count = 1
    for file_name in file_names:
        if '~$' not in file_name:
            file_path = os.path.join(file, file_name)                                                                   # 将文件路径与文件名连接在一起
            print("开始处理:",file_name)
            update_doc(file_path)                                                                                       # 更新目录
            ticks_3 = time.time()
            print(count,'>>',file_name,"处理完成!",time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(ticks_3)))
            log_str = str(count)+'>>'+file_name+"处理完成!"+time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(ticks_3))
            #log.logger.info(log_strT)
            count = count + 1
    print('文件处理完成!')


if __name__== "__main__" :
    run()


class Logger(object):
    level_relations = {
        'debug':logging.DEBUG,
        'info':logging.INFO,
        'warning':logging.WARNING,
        'error':logging.ERROR,
        'crit':logging.CRITICAL
    }#日志级别关系映射

    def __init__(self,filename,level='info',when='D',backCount=3,fmt='%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s'):
        self.logger = logging.getLogger(filename)
        format_str = logging.Formatter(fmt)#设置日志格式
        self.logger.setLevel(self.level_relations.get(level))#设置日志级别
        sh = logging.StreamHandler()#往屏幕上输出
        sh.setFormatter(format_str) #设置屏幕上显示的格式
        th = handlers.TimedRotatingFileHandler(filename=filename,when=when,backupCount=backCount,encoding='utf-8')#往文件里写入#指定间隔时间自动生成文件的处理器
        #实例化TimedRotatingFileHandler
        #interval是时间间隔,backupCount是备份文件的个数,如果超过这个个数,就会自动删除,when是间隔的时间单位,单位有以下几种:
        # S 秒
        # M 分
        # H 小时、
        # D 天、
        # W 每星期(interval==0时代表星期一)
        # midnight 每天凌晨
        th.setFormatter(format_str)#设置文件里写入的格式
        self.logger.addHandler(sh) #把对象加到logger里
        self.logger.addHandler(th)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值