Вопрос

I have the function below that copies a file in a directory and recreate it in the directory where the function is called. When I am running the code part by part in ipython, it is working fine. However, when I execute it as a function it is giving me the following error:

---> 17     shutil.copy2(filein[0], os.path.join(dir,'template.in'))

TypeError: 'type' object is not subscriptable

Here is the function

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'))

Any ideas about the error? Thanks

EDIT: Here is the code for 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

EDIT2: Output of filein from ipython

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

Basically, there is just one file. I used filein[0] in shutil.copy2 to remove the square brackets

Нет правильного решения

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top