2

I'm trying to create a simple docx to pdf converter and it throws me this problem:

Exception has occurred: com_error (-2147352567, 'Exception occurred.', (0, 'Microsoft Word', 'Sorry, we couldn’t find your file. Is it possible it was moved, renamed or deleted?\r (C:\Windows\system32\document1.docx)', 'wdmain11.chm', 24654, -2146823114), None)

import os
filesToConvertPath = os.getcwd() + r'\docxFiles'
folderWithPdfFIles = os.getcwd() + r'\pdfFiles'
for i in range(len(os.listdir(filesToConvertPath))):
    convert(os.listdir(filesToConvertPath)[i], folderWithPdfFIles)

.py file is in the main folder, with 2 subfolders, docxFiles and pdfFiles

Chris 789
  • 41
  • 1
  • 1
    If you are using office from 2010 onwards, don't waste your time: You can save as a pdf file directly from Word. – cup Jul 04 '22 at 19:48
  • No, its 2007. Also it is a LOT of files – Chris 789 Jul 04 '22 at 19:54
  • 1
    Where are you running your script from? If it is from a cmd prompt, are you cd'ing to the directory and then running or running directly from C:\windows\system32? – cup Jul 04 '22 at 19:56
  • 1
    Note that the results from `os.listdir()` can only be interpreted _relative to the path you passed to `os.listdir()`_. Consider doing an `os.chdir(filesToConvertPath)` to make that your current directory so everything is evaluated relative to that location before you start calling `convert()`; if you don't do that, you'll want to use `os.path.join()` on the paths that come back from `listdir` before you try to use them. – Charles Duffy Jul 04 '22 at 19:59
  • @cup I am running it from the main folder, not cmd prompt, code opened in code editor – Chris 789 Jul 04 '22 at 20:10
  • @CharlesDuffy Thank you , your idea worked. I had to chdir() to the folder with docx files, convert them and then chdir() to the folder with pdf files to combine them – Chris 789 Jul 05 '22 at 08:23

1 Answers1

0

Recommend:

  1. Replacing os.getcwd() to ensure you get the folder of your .py and not of Python:
import os
from pathlib import Path
from docx2pdf import convert

current_folder = Path(__file__).parent.resolve()

filesToConvertPath = os.path.join(current_folder, "docxFiles")
folderWithPdfFIles = os.path.join(current_folder, "pdfFiles")  
  1. (Optional) Replacing looping over Word docs to providing input and output folder. docx2pdf allows batch converting and outputting using folders (as well as single files) (documentation).

Replace:

for i in range(len(os.listdir(filesToConvertPath))):
    convert(os.listdir(filesToConvertPath)[i], folderWithPdfFIles)

With:

convert(filesToConvertPath, folderWithPdfFIles)
hlin03
  • 125
  • 7