我想将所有.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])
Run Code Online (Sandbox Code Playgroud)
但是它给了我一个错误:OSError:[Errno 2]没有这样的文件或目录
dsh*_*man 16
这是一个对我有用的解决方案。提出的其他解决方案在我使用 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)
Run Code Online (Sandbox Code Playgroud)
我更喜欢使用glob该模块来完成此类任务。将其放入文件中doc2docx.py。要使其可执行,请设置chmod +x. 也可以选择将该文件放入您的文件中$PATH,以使其“随处”可用。
#!/usr/bin/env python
import glob
import subprocess
for doc in glob.iglob("*.doc"):
subprocess.call(['soffice', '--headless', '--convert-to', 'docx', doc])
Run Code Online (Sandbox Code Playgroud)
尽管理想情况下您会将扩展留给 shell 本身,并doc2docx.py使用文件作为参数进行调用,例如doc2docx.py *.doc:
#!/usr/bin/env python
import subprocess
import sys
if len(sys.argv) < 2:
sys.stderr.write("SYNOPSIS: %s file1 [file2] ...\n"%sys.argv[0])
for doc in sys.argv[1:]:
subprocess.call(['soffice', '--headless', '--convert-to', 'docx', doc])
Run Code Online (Sandbox Code Playgroud)
根据@pyd的要求,要输出到目标目录,myoutputdir请使用:
#!/usr/bin/env python
import subprocess
import sys
if len(sys.argv) < 2:
sys.stderr.write("SYNOPSIS: %s file1 [file2] ...\n"%sys.argv[0])
for doc in sys.argv[1:]:
subprocess.call(['soffice', '--headless', '--convert-to', 'docx', '--outdir', 'myoutputdir', doc])
Run Code Online (Sandbox Code Playgroud)
用于os.path.join指定正确的目录。
import os, subprocess
main_dir = os.path.join('/', 'Users', 'username', 'Desktop', 'foldername')
for filename in os.listdir(main_dir):
if filename.endswith('.doc'):
print filename
subprocess.call(['soffice', '--headless', '--convert-to', 'docx', filename])
Run Code Online (Sandbox Code Playgroud)