# RE: file I/O and arithmetic calculation

Discussion in 'Python' started by Carlos Nepomuceno, May 22, 2013.

1. ### Carlos NepomucenoGuest

Funny! I made a lot of assumptions regarding your requirements specification. Let me know if it isn't what you need:

### 1strow_average.py ###
#Assuming you have CSV (comma separated values) files such as:
#1.txt = '0,1,2,3,4,5,6,7,8,9\n' \
#        '10,11,12,13,14,15,16,17,18,19\n' \
#        '20,21,22,23,24,25,26,27,28,29\n' ....
#
# Usage: contents[file][row][column]
# contents[0]       : file '1.txt'
# contents[1][2]    : 3rd row of file '2.txt'
# contents[3][4][5] : 6th column of 5th row of file '4.txt'
# len(contents)     : quantity of files
# len(contents[4])  : quantity of lines in file '5.txt'
# len(contents[4][0]: quantity of values in the 1st line of file '5.txt'

filenames = ['1.txt', '2.txt', '3.txt', '4.txt', '5.txt']
contents  = [[[int(z) for z in y.split(',')] for y in open(x).read().split()] for x in filenames]
s1c  = [sum([r[0] for r in f]) for f in contents]
a1r  = [sum(f[0])/float(len(f[0])) for f in contents]
print '\n'.join([x for x in ['File "{}" has 1st row average = {:.2f}'.format(n,a1r) if s1c==50 else '' for i,n in enumerate(filenames)] if x])

________________________________
> From:
> Date: Thu, 23 May 2013 01:13:19 +0900
> Subject: file I/O and arithmetic calculation
> To:
>
>
> Dear all,
>
> I would appreciate if someone could write a simple python code for the
> purpose below:
>
> I have five text files each of 10 columns by 10 rows as follows:
>
>
>
> file_one = 'C:/test/1.txt'
> file_two = 'C:/test/2.txt'
> . . .
> file_five = 'C:/test/5.txt'
>
> I want to calculate the mean of first row (10 elements) for each file
> (5 files), if mean of first column (10 elements) of each file (5
> files) is 50.
>
>
> Keira
>
>
> -- http://mail.python.org/mailman/listinfo/python-list

Carlos Nepomuceno, May 22, 2013