Python Document()函数保存失败:找不到目标文件路径
问题分析与解决方案
错误核心原因
触发FileNotFoundError的关键问题有两个:
qvr_bundle目录不存在时,python-docx的save方法无法自动创建目录,导致无法写入文件- 打包为
envisage2.exe后,程序的当前工作目录可能并非envisage文件夹,导致相对路径qvr_bundle解析错误,找不到目标目录
修复步骤
1. 确保目标目录存在
在保存文件前,先检查并创建qvr_bundle目录,避免因目录缺失导致写入失败:
# 在保存文档前添加以下代码 os.makedirs(bundle_path, exist_ok=True)
2. 使用绝对路径定位资源(解决exe打包后的路径失效问题)
打包成exe后,相对路径会失效,需基于程序所在目录生成绝对路径,确保始终能找到qvr_bundle和qvr_templates:
import sys import os from tkinter import filedialog, messagebox from docx import Document import openpyxl def on_qvr_click(): # 获取程序根目录(exe或脚本所在的envisage文件夹) if getattr(sys, 'frozen', False): # 打包成exe时的路径 root_dir = os.path.dirname(sys.executable) else: # 脚本运行时的路径 root_dir = os.path.dirname(os.path.abspath(__file__)) file_path = filedialog.askopenfilename(filetypes=[("Excel Files", "*.xlsx;*.xlsm")]) if file_path: print(f"Selected file: {file_path}") # 用根目录拼接绝对路径 bundle_path = os.path.join(root_dir, "qvr_bundle") template_dir = os.path.join(root_dir, "qvr_templates") 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(template_dir, 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) # 确保目录存在,不存在则创建 os.makedirs(bundle_path, exist_ok=True) combined_document.save(os.path.join(bundle_path, "combined_template.docx")) messagebox.showinfo("Success", "QVR bundle created successfully!") os.startfile(bundle_path)
3. 打包时的额外配置
如果用PyInstaller打包exe,需通过参数将资源目录包含进去,避免运行时找不到模板和输出目录:
pyinstaller --add-data "qvr_bundle;qvr_bundle" --add-data "qvr_templates;qvr_templates" envisage2.py
内容的提问来源于stack exchange,提问作者Ruben Adriaanse
相关产品推荐
相关产品推荐

