我想将大约 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))
如何避免此错误?
最佳答案
您是否尝试过使用 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 遇到了相同的错误。当我像这样 FileIO(pdf_path, "rb")
将 PDF 文件包装在 FileIO
中时,错误消失了,我能够成功处理该文件。
关于Python docx 属性错误 : 'WindowsPath' object has no attribute 'seek' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53591660/