一个简单的解决方案是像这样使用os.system。
import os
os.system("'Path_to_your_word_exe' 'path_to_your_p df'")
在这个方案中,路径中的空格有问题,所以我建议使用子进程调用。
import subprocesss
subprocess.call([r'raw path to word', r'raw path to file'])
subprocess.call([r'C:\Program Files\Microsoft Office\root\Office16\WINWORD.exe', r'C:\Users\gopco\Downloads\SCYR.pdf'])
要对一个目录中的多个文件进行自动化作业,请使用以下代码。
import win32com.client
import os
#start word
word = win32com.client.Dispatch("Word.Application")
#allow word to print error messages (if any)
word.visible = 1
pdfs_path = "./" # folder with pdfs
reqs_path = "./" # folder for saving docx files
for i, doc in enumerate(glob.iglob(pdfs_path+"*.pdf")):
filename = doc.split('\\')[-1] #get just the file name
in_file = os.path.abspath(doc) #absolute path
print(in_file)
wb = word.Documents.Open(in_file) #open the pdf in word
out_file = os.path.abspath(reqs_path +filename[0:-4]+ ".docx".format(i)) #set the filename for saving the docx
print("outfile\n",out_file)
wb.SaveAs2(out_file, FileFormat=16) # file format for docx