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

标签 python .doc

我想将特定文件夹中的所有 .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] 没有那个文件或目录

最佳答案

这是一个对我有用的解决方案。提出的其他解决方案在我使用 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)

关于python - 使用 python 将多个 .doc 转换为 .docx 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38468442/

相关文章:

python - 我无法弄清楚我的 Python Socket 错误

python - 将一个Integer值转换为base64,然后解码得到明文

c++ - 可以使用 Qt 输出为 .doc 格式吗?

java - 如何读取 .doc 文件中的图像

ios - iPhone/iPad 版本的 Dropbox 如何显示 Microsoft Word 文档?

c# 将 .docx 文件加载到 richtextbox 中花费的时间太长

python /Django : Is it wise to use "Item" as a class name in Python (in Django in this case)?

python - 在 Tensorflow 中查找子矩阵的秩

python - Pyomo 时间相关模型?