批量将.doc文件转换为.docx文件的Python脚本优化

在本篇博客中,我将分享如何使用Python编写一个脚本,可以批量将一个文件夹中的所有.doc文件转换为.docx文件。这个脚本利用了Python的win32com库来操作Word应用程序进行文件格式转换,并通过tkinter库中的filedialog模块实现文件夹选择对话框,让用户选择需要转换的文件夹路径。

首先,我们定义了两个函数:doc_to_docx用于将单个.doc文件转换为.docx文件,convert_all_docs_in_folder用于遍历文件夹中的所有文件并将.doc文件转换为.docx文件。在主程序中,我们创建了一个Tk root窗口并隐藏,然后通过filedialog.askdirectory()方法弹出文件夹选择对话框,让用户选择需要转换的文件夹路径。

import os
import win32com.client
from tkinter import filedialog
from tkinter import Tk
import logging

def doc_to_docx(doc_path):
    try:
        with win32com.client.Dispatch("Word.Application") as word:
            word.Visible = 0
            doc = word.Documents.Open(doc_path)
            docx_path = os.path.splitext(doc_path)[0] + '.docx'
            doc.SaveAs(docx_path, FileFormat=16)
            logging.info(f"Converted: {doc_path} to {docx_path}")
            return docx_path
    except Exception as e:
        logging.error(f"Failed to convert {doc_path} due to {str(e)}")
        return None

def convert_all_docs_in_folder(folder_path):
    for file_name in os.listdir(folder_path):
        full_file_name = os.path.join(folder_path, file_name)
        if os.path.splitext(file_name)[-1].lower() == '.doc':
            docx_path = doc_to_docx(full_file_name)
            if docx_path:
                os.remove(full_file_name)

if __name__ == '__main__':
    logging.basicConfig(level=logging.INFO)
    
    root = Tk()
    root.withdraw()
    
    folder_path = filedialog.askdirectory()
    if folder_path:
        convert_all_docs_in_folder(folder_path)

为了优化代码,我们减少了全局变量的使用,使用with语句管理Word应用程序对象的生命周期,添加了异常处理以及日志记录。通过这些优化,我们可以确保程序的稳定性和可维护性。

你可能感兴趣的:(python,c#,microsoft)