Python docx AttributeError: 'WindowsPath' 对象没有属性 'seek'

新手上路,请多包涵

我想将大约 250 张图像及其文件名插入到 docx 文件中。

我的 test.py 文件:

 from pathlib import Path
import docx
from docx.shared import Cm

filepath = r"C:\Users\Admin\Desktop\img"
document = docx.Document()

for file in Path(filepath).iterdir():
#    paragraph = document.add_paragraph(Path(file).resolve().stem)
    document.add_picture(Path(file).absolute(), width=Cm(15.0))

document.save('test.docx')

调试后我得到这个错误:

 Exception has occurred: AttributeError
'WindowsPath' object has no attribute 'seek'
  File "C:\Users\Admin\Desktop\test.py", line 10, in <module>
    document.add_picture(Path(file).absolute(), width=Cm(15.0))

我怎样才能避免这个错误?

原文由 05x 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.1k
1 个回答

您是否尝试过使用 io.FileIO

 from io import FileIO

from pathlib import Path
import docx
from docx.shared import Cm

filepath = r"C:\Users\Admin\Desktop\img"
document = docx.Document()

for file in Path(filepath).iterdir():
#    paragraph = document.add_paragraph(Path(file).resolve().stem)
    document.add_picture(FileIO(Path(file).absolute(), "rb"), width=Cm(15.0))

document.save('test.docx')

在将文件路径传递给 PdfFileReader 时,我使用 PyPDF2 遇到了同样的错误。当我将 PDF 文件包装在 FileIO 就像这样 FileIO(pdf_path, "rb") 错误消失了,我能够成功处理文件。

原文由 wtee 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题