在python中对多个对象重复相同的方法

时间:2014-09-20 09:27:55

标签: python list pandas

这是非常基本但我无法通过谷歌找到答案。我有一个循环,将大量文本文件导入到pandas数据帧中。

我已将名字写入清单。

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)

我现在希望在每个对象上运行to_sql()方法,但似乎无法找到正确的语法。根据我的理解,对象已经实例化,但解释器认为我正在尝试操作字符串对象。

然后我获取pandas对象列表

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

并尝试使用方法循环

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 

我确信这是非常基本的,我很感激你的帮助。

1 个答案:

答案 0 :(得分:1)

问题似乎在这里:

 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

我已经在每个阶段添加了评论。在加载数据帧时 - 您永远不会保存它们!您只能将他们的名字保留在列表中。