将元素添加到Python列表中时出现'AttributeError'
问题描述:
我对Python更新,我无法保存重命名文件的列表,因此我最终可以将文件移动到新目录。我的代码贴在下面:将元素添加到Python列表中时出现'AttributeError'
import os
new_files = []
for orig_name in orig: #This loop splits each file name into a list of stings containing each word
if '.' in orig_name: #This makes sure folder names are not changed, only file names
base = os.path.splitext(orig_name)[0]
ext = os.path.splitext(orig_name)[1]
sep = base.split() #Separation is done by a space
for t in sep: #Loops across each list of strings into an if statement that saves each part to a specific variable
if t.isalpha() and len(t) == 3:
wc = t
wc = wc.upper()
elif len(t) > 3 and len(t) < 6:
wc = t
wc = wc.upper()
elif len(t) >= 4:
pnum = t
if pnum.isalnum:
pnum = pnum.upper()
elif t.isdecimal() and len(t) < 4:
opn = t
if len(opn) == 2:
opn = '0' + opn
else:
pass
new_nam = '%s OP %s %s' % (pnum, opn, wc) #This is the variable that contain the text for the new name
new_nam = new_nam + ext
new_files = new_files.append(new_nam)
print(new_files)
基本上这个代码是什么在原来的文件名(原稿)循环,并将其重命名为特定的约定(NEW_NAME)。我遇到的问题是每次迭代,我想每个new_nam保存到列表中的“new_files”不过,我不断收到此错误:
line 83, in <module>
new_files = new_files.append(new_nam)
AttributeError: 'NoneType' object has no attribute 'append'
基本上,我认为这是说你不能添加一个“无类型“到一个有意义的列表,但是当我打印所有new_nam的时候,它们都是不是None类型的字符串。所以我想我不知道为什么这个代码没有将每个新文件名添加到new_files列表中。任何提示的建议非常感谢,不能找出这一个:/谢谢!
答
list.append
是就位操作。你必须调用函数不分配返回值:
In [122]: data = [1, 2, 3]
In [123]: data.append(12345)
In [124]: data
Out[124]: [1, 2, 3, 12345]
在你的情况,你需要
new_files.append(new_nam)
所有list.___
方法如list
docs描述的就地。
哦哇我知道这是愚蠢的,谢谢你,每天学习新的东西! – Bkal05
@ Bkal05没问题。不要忘记,如果它有帮助,你可以标记一个可接受的答案。 –