K.Pil
K.Pil

Reputation: 986

python-docx package can not read the image file

I am using python-docx package to create word documents. When I write :

directory=r'folder'
document.add_picture("./folder/Bamboo Shoots.jpg")

Able to see an image file in the word document

Iterating through the file list directory :

for filename in os.listdir(directory):
   document.add_picture('./folder/'+filename)

I get docx.image.exceptions.UnrecognizedImageError exception

All images under the folders are .jpg files. Why would the same operation fail when iterating through the directory list?

Can anyone please explain the different behavior?

Upvotes: 1

Views: 751

Answers (1)

Stefan
Stefan

Reputation: 957

It is a good idea to add if statements that check whether it is a file and whether it is a JPG. That should avoid problems.

directory = r"folder"
filenames = os.listdir(directory)

document = Document()

for index, filename in enumerate(filenames): # loop through all the files for adding pictures
    if os.path.isfile(os.path.join(os.path.abspath(directory), filename)): # check whether the current object is a file or not
        if filename[len(filename)-3: len(filename)].upper() == 'JPG': # check whether the current object is a JPG file
            
            #Add images
            document.add_picture(os.path.join(os.path.abspath(directory), filename))

Upvotes: 1

Related Questions