Repeat same method on multiple objects in python
Question: This is very basic but I am having trouble finding an answer through google. I
have a loop that imports a number of text files into pandas dataframes.

I have written the names to a list.

    
    
    onlyfiles = [ f for f in listdir(mypath) if isfile(join(mypath,f)) and join(mypath,f).endswith('.txt') ]
    
    dataframelist = []
    
    for filenum in range(1,len(onlyfiles)):
     path = 'path/%s' % onlyfiles[filenum]
     print path
     name = onlyfiles[filenum][:-4]
     dsname = name
     print name
     name = pd.read_csv(path, sep = '\t')
     print '%s has been imported' % dsname
     dataframelist.append(dsname)
    

I am now looking to run the to_sql() method on each object but cannot seem to
find the right syntax. The objects are already instantiated, to my
understanding but the interpreter thinks I am trying to manipulate string
objects.

I then take the list of pandas objects

    
    
    #if a dataframe exists and has a '-customer' at the end then import
    
    custlist = []
    
    for item in list(dataframelist):
      if item.endswith('-customer'):
            custlist.append(item)
    

and try and loop with the method

    
    
    for dsname in range(1,5):
        ds_to_sql = custlist[dsname]
        print ds_to_sql
        (ds_to_sql.to_sql('%s', engine)) % ds_to_sql 
    

I am sure this is quite basic and I appreciate the assistance.


Answer: The problem seems to be here:

    
    
     name = onlyfiles[filenum][:-4] #name = 'example.txt'
     dsname = name #dsname = name = 'example.txt'
     print name
     name = pd.read_csv(path, sep = '\t') #name = DataFrame
     print '%s has been imported' % dsname
     dataframelist.append(dsname) #'example.txt' is appended
    

I've added comments with what's happenning at each stage. While you are
loading your dataframes - you never save them! You only keep their names in
the list.

