Search code examples
pythonpython-3.xpyinstallerdocx

Python docx Document() function not working as expected


I am trying to make a function called on_qvr_click that takes an Excel file as input and reads the column named qvr_files. For each cell in this column, it looks for a corresponding .docx file in the qvr_templates directory. It then combines the contents of these template files into a single word document and saves it in the qvr_bundle directory with the name combined_template.docx.

Here is my code:

def on_qvr_click():
    file_path = filedialog.askopenfilename(filetypes=[("Excel Files", "*.xlsx;*.xlsm")])
    if file_path:
        print(f"Selected file: {file_path}")
        bundle_path = os.path.join("qvr_bundle")
        wb = openpyxl.load_workbook(file_path)
        ws = wb.active
        qvr_files_col = None
        for col in ws.iter_cols():
            if col[0].value == "qvr_files":
                qvr_files_col = col
                break
        if qvr_files_col:
            combined_document = Document()
            for cell in qvr_files_col[1:]:
                if cell.value:
                    template_path = os.path.join("qvr_templates", f"{cell.value}.docx")
                    if os.path.exists(template_path):
                        template_document = Document(template_path)
                        for element in template_document.element.body:
                            combined_document.element.body.append(element)
            combined_document.save(os.path.join(bundle_path, "combined_template.docx"))
        messagebox.showinfo("Success", "QVR bundle created successfully!")
        os.startfile(bundle_path)

And here is my directory structure:

-> envisage
--> qvr_bundle
--> qvr_templates
---> 010AHU.docx
---> 012FCU.docx
--> static_files
--> envisage2.exe

But when running the program the Document() function throws an error, saying it cannot find the template .docx file:

    combined_document.save(os.path.join(bundle_path, "combined_template.docx"))  File "C:\Users\ruben\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\docx\document.py", line 135, in save
    self._part.save(path_or_stream)
  File "C:\Users\ruben\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\docx\parts\document.py", line 111, in save    self.package.save(path_or_stream)
  File "C:\Users\ruben\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\docx\opc\package.py", line 172, in save
    PackageWriter.write(pkg_file, self.rels, self.parts)
  File "C:\Users\ruben\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\docx\opc\pkgwriter.py", line 32, in write
    phys_writer = PhysPkgWriter(pkg_file)
  File "C:\Users\ruben\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\docx\opc\phys_pkg.py", line 141, in __init__
    self._zipf = ZipFile(pkg_file, 'w', compression=ZIP_DEFLATED)
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2800.0_x64__qbz5n2kfra8p0\lib\zipfile.py", line 1249, in __init__
    self.fp = io.open(file, filemode)
FileNotFoundError: [Errno 2] No such file or directory: 'qvr_bundle\\combined_template.docx'

I cant figure out why it is throwing this error


Solution

  • I managed to solve it, found the answer here:

    https://stackoverflow.com/a/73289012/15163302

    The two documents I am trying to combine are empty, and thats why its throwing an error!

    As soon as I put something in the documents, it worked.