存储阵列中多个文件的数据列表

时间:2013-04-17 12:01:30

标签: python file-io tkinter

好吧我正在做的是仅获取ONE .log文件的内容,将其存储在一个数组中,然后将其输出到多个列表框中,如下所示:

filelog_ext=".log" #log extension

#open one log file
f = open("%s\%s%s" % (path,filename,filelog_ext),"r")
#init aray      
array = []
#copy contents of file to array
for line in f:
    array.append( line )
f.close()
#insert each array content to multilistbox
self.mlb.insert (END, ('%s' % (array[0]),'%s' % (array[1]),'%s' % (array[2]),'%s' % array[3])))
    self.mlb.pack (expand=YES,fill=BOTH)

我现在要做的是获取MANY .log文件的内容,将它们输出到数组中,然后将它们输出到多个列表框中。

我尝试了以下但是它似乎不起作用:

for files in os.listdir("."):        
        if files.endswith(".log"):  #this will take all my files ending with .log

    #not sure how to go about and take all files ending with .log, copying them to array and saving them to the multilistbox mlb

有人可以帮助我吗?

更新: @john zwink 我试图整合你的代码不知道我是否正确的方式,但它仍然无法正常工作。错误是“索引列表超出范围”

    path = "C:\sdmdownloads"        
    array = []
    for filename in glob.iglob(os.path.join(path, filelog_ext)):
       with open(filename) as f:
           array.extend(f)
           self.mlb.insert (END, ('%s' % (array[0]),'%s' % (array[1]),'%s' % (array[2]),'%s' % (array[3])))
           self.mlb.pack (expand=YES,fill=BOTH)

1 个答案:

答案 0 :(得分:0)

这样的东西?

import glob
import os

filelog_ext=".log" #log extension
array = []

for filename in glob.iglob(os.path.join(path, filelog_ext)):
    with open(filename) as f:
        array.extend(f)