Reputation: 986
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
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