python docx包无法读取图像文件

python docx包无法读取图像文件,python,python-docx,Python,Python Docx,我正在使用PythonDocx包创建word文档。 当我写作时: directory=r'folder' document.add_picture("./folder/Bamboo Shoots.jpg") 能够在word文档中查看图像文件 在文件列表目录中迭代: for filename in os.listdir(directory): document.add_picture('./folder/'+filename) I get docx.image.exc

我正在使用PythonDocx包创建word文档。 当我写作时:

directory=r'folder'
document.add_picture("./folder/Bamboo Shoots.jpg")
能够在word文档中查看图像文件

在文件列表目录中迭代:

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

I get docx.image.exceptions.UnrecognizedImageError exception
文件夹下的所有图像都是.jpg文件。为什么在遍历目录列表时相同的操作会失败


有人能解释一下不同的行为吗?

最好添加if语句,检查它是否是文件,是否是JPG。这应该可以避免问题

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


/folder
文件夹中是否有文件夹?该目录中是否有隐藏文件,而不是图像?例如
.file
。因为如果是这种情况,那可能就是错误的原因。我检查了文件夹,没有隐藏的文件和foldersThanks,上面的代码也出现了同样的异常,这很奇怪,因为我在一个目录中使用了很多JPG文件。可能您的文件已损坏?看起来文件图像标题已损坏。我使用枕头包以相同的格式读取和保存文件。这个过程隐藏了图像标题,我能够将图像写入word文件。