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
I don’t see how you can possibly get
'type' object is not subscriptablewith this code (as a matter of fact, I can successfully run it on my computer and have it copy one file).This suggests that the code you’re running isn’t the code that you think you’re running.
I would do two things:
ipython(to eliminate the possibility that you’re accidentally calling an older version offind()that got imported earlier).As a side note, I’d explicitly handle the case where
fileinis empty: the current code would raise an exception (list index out of range).