这感觉应该很简单,但我没有主意。
我正在尝试运行一个相当简单的脚本,以获取包含文本的 Markdown 文件的文件夹,然后将其转换为单个正在运行的 .docx 文件。由于某种原因,无论我做什么,我都会遇到相同的错误问题。
Traceback (most recent call last):
File "c:\PATH\markdown_conversion.py", line 52, in <module>
append_docx_to_existing(existing_docx, docx_file)
File "c:\PATH\markdown_conversion.py", line 25, in append_docx_to_existing
doc = Document(existing_file)
^^^^^^^^^^^^^^^^^^^^^^^
File "c:\PATH\.conda\envs\AnnLetters\Lib\site-packages\docx\api.py", line 27, in Document
document_part = cast("DocumentPart", Package.open(docx).main_document_part)
^^^^^^^^^^^^^^^^^^
File "c:\PATH\.conda\envs\AnnLetters\Lib\site-packages\docx\opc\package.py", line 127, in open
pkg_reader = PackageReader.from_file(pkg_file)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "c:\PATH\.conda\envs\AnnLetters\Lib\site-packages\docx\opc\pkgreader.py", line 22, in from_file
phys_reader = PhysPkgReader(pkg_file)
^^^^^^^^^^^^^^^^^^^^^^^
File "c:\PATH\.conda\envs\AnnLetters\Lib\site-packages\docx\opc\phys_pkg.py", line 21, in __new__
raise PackageNotFoundError("Package not found at '%s'" % pkg_file)
docx.opc.exceptions.PackageNotFoundError: Package not found at 'c:/PATH/comp_letters.docx'
我已经验证了正确的路径,尝试创建新文件并重新启动多次。感觉应该不会太复杂。
我从来没有弄清楚问题是什么,但我能够通过仅从 Markdown 读取文本并将其添加到 .docx 文件中来简化我的脚本,而不是在附加到其他文档之前将 Markdown 转换为 .docx。看来问题已经解决了。
import os
import glob
from docx import Document
# Directory containing the markdown files
directory = "C:/PATH/markdown"
# Existing .docx file
existing_docx = "C:/PATH/comp_letters.docx"
def append_text_to_existing(existing_file, markdown_file):
# Open the existing .docx file
with open(existing_file, 'a') as docx_file:
# Open the markdown file and read the text
with open(markdown_file, 'r', encoding='utf-8') as md_file:
md_text = md_file.read()
# Append the text to the .docx file
docx_file.write(md_text)
# Get all the markdown files in the directory
markdown_files = glob.glob(os.path.join(directory, '*.md'))
# Append each markdown file to the existing .docx existing file
for markdown_file in markdown_files:
# Use the function
append_text_to_existing(existing_docx, markdown_file)