我想将特定文件夹中的所有 .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/