调用函数时出现'不可下标'错误

2 投票
2 回答
1062 浏览
提问于 2025-04-17 10:47

我有一个函数,它的作用是把一个文件复制到一个目录里,并在调用这个函数的地方重新创建这个文件。当我在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'))

有没有人知道这个错误是什么原因呢?谢谢

补充:这是find的代码

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

补充2:在ipython中filein的输出结果

  [1]: filein
  [2]: ['/home/Projects/test.in']

基本上,只有一个文件。我在shutil.copy2中使用了filein[0],这样就去掉了方括号

2 个回答

0

使用

import pdb
pdb.pm()

在捕捉到异常之后,可以准确找到是哪个文件中的哪一行代码引发了错误,以及哪个变量的类型被下标访问了。

1

我看不出你怎么会在这段代码中遇到 'type' object is not subscriptable 这个错误(实际上,我在我的电脑上成功运行了这段代码,并且可以复制一个文件)。

这说明你运行的代码可能和你 认为 运行的代码不一样。

我会做两件事:

  1. 确保代码和你在问题中写的一模一样;
  2. 因为你似乎是在一个交互式的环境中运行这个代码,确保你关闭并重启 ipython(这样可以避免你不小心调用了之前导入的旧版本的 find() 函数)。

另外,我建议你明确处理 filein 为空的情况:现在的代码会引发一个异常(list index out of range)。

撰写回答