首页 > 解决方案 > AttributeError: 'NoneType' object has no attribute 'name' 当我尝试获取 docx 文件的标题时发生错误

问题描述

我是 python 编程的新手。我正在使用docx模块来处理文档。当我尝试使用从 docx 文件中读取标题时paragraph.style.name,我得到:

AttributeError: 'NoneType' object has no attribute 'name'

我的脚本:

from docx import Document  
document=Document('C:\\Users\\abc\\Desktop\\check\\Leave_Policy_converted.docx')
for paragraph in document.paragraphs:
    if paragraph.style.name == 'Heading 1':
        print (paragraph.text)

请澄清一下。先感谢您。

标签: pythonpython-3.xpython-docx

解决方案


这意味着您正在访问属性的东西是None(不是真正的值)。

你需要检查paragraph.style它是否是None,而不是访问.style.name

if paragraph.style is not None and paragraph.style.name == 'Heading 1':
  print(paragraph.text)

推荐阅读