Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python docx AttributeError: 'WindowsPath' object has no attribute 'seek'

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?

like image 393
05x Avatar asked Oct 24 '25 14:10

05x


2 Answers

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.

like image 118
wtee Avatar answered Oct 27 '25 05:10

wtee


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))
like image 29
Cliu Avatar answered Oct 27 '25 04:10

Cliu