Sums of entries, Python
Question: > **Possible Duplicate:**  
>  [summing up values of columns from multiple
> files](http://stackoverflow.com/questions/14712268/summing-up-values-of-
> columns-from-multiple-files)

I have a small problem here, I'm trying to sum up entries from multiple files
(50), and each of them contain 3 columns. for example, using the first 3
files: file1.txt, file2.txt, file3.txt which look like:

file1.txt:

    
    
    2 3 4
    1 5 6
    5 4 7
    

file2.txt:

    
    
    1 2 1
    2 3 2
    4 3 1
    

file3.txt:

    
    
    6 1 1
    1 3 0
    3 4 5
    

So my question is how do i sum up all the entries from column one, column two
and column three from the 50 files to end up with a file that looks like:

output.txt:

    
    
    9 6 6
    4 11 8
    12 11 13
    

I've read in the 50 files and appended them but I'm having trouble actually
summing the entries one by one.

so I've done this:

    
    
    for p in range(50):
        locals()['first_col%d' % p] = []
        locals()['second_col%d' % p] = []
        locals()['third_col%d' % i] = []
    
    for i in range(1,50):
        f = open("file"+str(i)+".txt","r")
        for line in f:
            locals()['fist_col%d' % i].append(float(line.split()[0]))
            locals()['second_col%d' % i].append(float(line.split()[1]))
            locals()['third_col%d' % i].append(float(line.split()[2]))
    
    f.close()
    

I'm trying to think of a way to put this in a loop that will read in all the
`first_cols` (`first_col1` ,`first_col2`, `first_col3`, etc), `second_cols`
and `third_cols` and sum up the entries.


Answer: You could use `glob` to wildcard match the filename pattern, then a bit of
judicious use of `zip` and abuse `literal_eval` (might want to consider just a
generator to convert to `int` instead though) - NB - this expects the same
number of columns and rows for each file, otherwise truncation will occur:

    
    
    from glob import glob
    from ast import literal_eval
    
    filenames = glob('/home/jon/file*.txt')
    files = [open(filename) for filename in filenames]
    for rows in zip(*files):
        nums = [literal_eval(row.replace(' ', ',')) for row in rows]
        print map(sum, zip(*nums))
    
    [9, 6, 6]
    [4, 11, 8]
    [12, 11, 13]
    

