使用 python 将多个 .doc 转换为 .docx 文件

新手上路,请多包涵

我想将所有 .doc 文件从特定文件夹转换为 .docx 文件。

我尝试使用以下代码,

 import subprocess
import os
for filename in os.listdir(os.getcwd()):
    if filename.endswith('.doc'):
        print filename
        subprocess.call(['soffice', '--headless', '--convert-to', 'docx', filename])

但它给了我一个错误:OSError: [Errno 2] No such file or directory

原文由 sunil pawar 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 585
1 个回答

这是一个对我有用的解决方案。提出的其他解决方案在我使用 Python 3 的 Windows 10 机器上不起作用。

 from glob import glob
import re
import os
import win32com.client as win32
from win32com.client import constants

# Create list of paths to .doc files
paths = glob('C:\\path\\to\\doc\\files\\**\\*.doc', recursive=True)

def save_as_docx(path):
    # Opening MS Word
    word = win32.gencache.EnsureDispatch('Word.Application')
    doc = word.Documents.Open(path)
    doc.Activate ()

    # Rename path with .docx
    new_file_abs = os.path.abspath(path)
    new_file_abs = re.sub(r'\.\w+$', '.docx', new_file_abs)

    # Save and Close
    word.ActiveDocument.SaveAs(
        new_file_abs, FileFormat=constants.wdFormatXMLDocument
    )
    doc.Close(False)

for path in paths:
    save_as_docx(path)

原文由 dshefman 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题