首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >python-docx包无法读取图像文件

python-docx包无法读取图像文件
EN

Stack Overflow用户
提问于 2020-12-06 06:04:57
回答 1查看 160关注 0票数 0

我正在使用python-docx包创建word文档。当我写道:

代码语言:javascript
运行
复制
directory=r'folder'
document.add_picture("./folder/Bamboo Shoots.jpg")

能够在word文档中查看图像文件

遍历文件列表目录:

代码语言:javascript
运行
复制
for filename in os.listdir(directory):
   document.add_picture('./folder/'+filename)

I get docx.image.exceptions.UnrecognizedImageError exception

文件夹下的所有图像都是.jpg文件。为什么在遍历目录列表时,相同的操作会失败?

谁能解释一下这种不同的行为?

EN

回答 1

Stack Overflow用户

发布于 2020-12-06 06:24:48

添加if语句来检查它是否是一个文件以及它是否是JPG是一个好主意。这应该可以避免出现问题。

代码语言:javascript
运行
复制
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))
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65162477

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档