我是python的新手,我在保存重命名文件列表时遇到问题,因此我最终可以将文件移动到新目录。我的代码发布在下面:
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)
基本上,此代码的作用是循环原始文件名(orig),并将它们重命名为特定约定(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列表中。非常感谢任何建议的建议,无法想出这一点:/谢谢!
答案 0 :(得分:2)
list.append
是 inplace 操作。您必须在不指定返回值的情况下调用该函数:
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
docs中描述的所有list.___
方法都已到位。