【记录一下】报错解决AttributeError: ‘NoneType‘ object has no attribute ‘text‘

【记录一下】报错解决AttributeError: 'NoneType' object has no attribute 'text'

问题

在运行xml转txt文件时出现下面的报错
在这里插入图片描述

原因是不同的xml文件中有的可能还有<difficult>0</difficult>,有的文件却没有,在原始的代码中无法解决这个问题
原始代码如下:
在这里插入图片描述

解决办法

改为下面的样子

 #difficult = obj.find('difficult').text
        if obj.find('difficult'):
            difficult = int(obj.find('difficult'.text))
        else:
            difficult = 0

在这里插入图片描述
后续运行成功。

来源于:记录错误:AttributeError: ‘NoneType‘ object has no attribute ‘text‘

猜你喜欢

转载自blog.csdn.net/weixin_45768644/article/details/129865608