我有下面的函数,它可以将一个文件复制到一个目录中,然后在调用该函数的目录中重新创建它。当我在 ipython 中逐部分运行代码时,它工作正常。但是,当我将它作为函数执行时,它会出现以下错误:
---> 17 shutil.copy2(filein[0], os.path.join(dir,'template.in'))
TypeError: 'type' object is not subscriptable
这是函数
import os
import shutil
from find import find
def recreatefiles(filedir):
currdir = os.getcwd() # get current directory
dirname = 'maindir'
dir = os.path.join(currdir,dirname)
if not os.path.exists(dir):
os.makedirs(dir)
#Copy .in files and create a template
filein = find('*.in',filedir) # find is a function created
shutil.copy2(filein[0], os.path.join(dir,'template.in'))
关于错误的任何想法?谢谢
编辑:这是查找的代码
import os, fnmatch
def find(pattern, path):
result = []
for root, dirs, files in os.walk(path):
for name in files:
if fnmatch.fnmatch(name, pattern):
if not name.startswith('.'):
result.append(os.path.join(root, name))
return result
EDIT2:从 ipython 输出 filein
[1]: filein
[2]: ['/home/Projects/test.in']
基本上,只有一个文件。我在 shutil.copy2 中使用了 filein[0] 来删除方括号
请您参考如下方法:
我不明白你怎么可能用这段代码得到 'type' object is not subscriptable(事实上,我可以在我的电脑上成功运行它并让它复制一个文件)。
这表明您正在运行的代码不是您认为正在运行的代码。
我会做两件事:
- 确保代码完全出现在您的问题中;
- 因为您似乎是在交互式 shell 中运行它,请确保关闭并重新启动
ipython(以消除您意外调用旧版本的find() 的可能性之前导入的)。
作为旁注,我会明确处理 filein 为空的情况:当前代码会引发异常(list index out of range)。
