Skip to main content
 首页 » 编程设计

python之涉及 "AttributeError: ' 的奇怪错误 NoneType' 对象没有属性 'append' "

2025年05月04日29xxx_UU

所以我试图通过将文本文件转换为列表并在空格处拆分列表中的每个项目来解析文本文件。

我已经创建了一个测试变量来单独运行这部分代码。 我在 spyder 编辑器中的代码:

test = ['NC_009142.1_03_012_002_001 560', 'NC_017586.1_13_009_003_001 555', 'NC_016111.1_13_010_003_001 555'] 
ListOfLinesParsed = test 
 
PN_List = [] 
counter_iterative = 0 
while counter_iterative < len(ListOfLinesParsed): 
    PN_List = PN_List.append(ListOfLinesParsed[counter_iterative].split()[0]) 
    counter_iterative += 1 
 
print PN_List 

返回错误:

runfile(r'/home/jake/.spyder2/.temp.py', wdir=r'/home/jake/.spyder2')

Traceback (most recent call last): 
 
  File "<stdin>", line 1, in <module> 
 
  File "/usr/lib/python2.7/dist- 
packages/spyderlib/widgets/externalshell/sitecustomize.py", line 493, in runfile 
 
    execfile(filename, namespace) 
  File "/home/jake/.spyder2/.temp.py", line 7, in <module> 
 
    PN_List = PN_List.append(ListOfLinesParsed[counter_iterative].split()[0]) 
 
AttributeError: 'NoneType' object has no attribute 'append' 

但是如果我直接在终端中输入命令,我不会出错:

testL = []

testL.append(test[0].split()[0])

testL

['NC_009142.1_03_012_002_001'] 

testL.append(test[1].split()[0])

testL

['NC_009142.1_03_012_002_001', 'NC_017586.1_13_009_003_001'] 

testL.append(test[2].split()[0])

testL

['NC_009142.1_03_012_002_001', 'NC_017586.1_13_009_003_001', 'NC_016111.1_13_010_003_001'] 

这两件事不应该完全一样吗?我不明白为什么我的脚本中的命令与终端命令的行为有任何不同。

请您参考如下方法:

线

PN_List = PN_List.append(ListOfLinesParsed[counter_iterative].split()[0]) 

是问题所在。

list.append 是一个就地操作,它返回None,但会改变原始列表本身。如果您将 PN_List 分配给结果,它将变为 None。如果不这样做,那么您的程序将顺利运行。这就是为什么当您尝试在没有分配的情况下附加内容时,您会得到预期的答案。