I want to insert about 250 images with their filename into a docx-file.
My test.py file:
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')
After Debugging I got this Error:
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))
How can i avoid this Error?
Have you tried using 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')
I encountered the same error using PyPDF2 when passing a file path to PdfFileReader. When I wrapped the PDF file in FileIO like so FileIO(pdf_path, "rb") the error went away and I was able to process the file successfully.
You need to convert the file object to a string type for the Path method.
for file in Path(filepath).iterdir():
# Paragraph = document.add_paragraph(Path(file).resolve().stem)
document.add_picture(Path(str(file)).absolute(), width=Cm(15.0))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With