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

18,466

Solution 1

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.

Solution 2

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))

Solution 3

In my case, changing the '/' for '\' in the path did the trick. Ex: "C:/Users/Admin/Desktop/img" (which I believe is probably what wrapping it in FileIO does, but in my case doing this didn't work)

You can also achieve that using

os.path.join(mydir, myfile)

as explained here https://stackoverflow.com/a/2953843/11126742

Solution 4

Simply cast the path object to string:

for file in Path(filepath).iterdir():
    path_str = str(Path(file).absolute())
    document.add_picture(path_str, width=Cm(15.0))

The problem with using WindowsPath object as an input seems to be that the document.add_picture does not know how to use that to open a file. The seek is a method of a file object.

Share:
18,466

Related videos on Youtube

05x
Author by

05x

Updated on June 04, 2022

Comments

  • 05x
    05x almost 2 years

    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?

  • Eborbob
    Eborbob almost 3 years
    This solved a similar issue for me - just put a str() around the file variable.