(This is my third answer, because I misunderstood what your code is doing in my original, and then made a small but critical mistake in my second, hopefully three charm.
Editing Since this seems to be a popular answer, I made a few changes to improve its implementation over the years, most of which are not very significant. This is so if people use it as a template, this will provide an even better foundation.
As others have pointed out, your MemoryError problem is most likely due to the fact that you are trying to read the entire contents of huge files in memory, and then, in addition to this, effectively double the amount of memory needed to create a list of lists of string values ​​from each line.
Python memory limits are determined by how much physical disk space and virtual memory on your computer and operating system is available. Even if you don’t use all of this and your program “works,” using it can be impractical because it takes too much time.
In any case, the most obvious way to avoid this is to process each file one line at a time, which means that you must do the processing step by step.
To do this, a list of current totals for each of the fields is saved. When this is completed, the average value of each field can be calculated by dividing the corresponding total value by the counter of all read lines. Once this is done, these averages can be printed, and some are written to one of the output files. I also consciously tried to use very descriptive variable names to try to understand them.
try: from itertools import izip_longest except ImportError: # Python 3 from itertools import zip_longest as izip_longest GROUP_SIZE = 4 input_file_names = ["A1_B1_100000.txt", "A2_B2_100000.txt", "A1_B2_100000.txt", "A2_B1_100000.txt"] file_write = open("average_generations.txt", 'w') mutation_average = open("mutation_average", 'w') # left in, but nothing written for file_name in input_file_names: with open(file_name, 'r') as input_file: print('processing file: {}'.format(file_name)) totals = [] for count, fields in enumerate((line.split('\t') for line in input_file), 1): totals = [sum(values) for values in izip_longest(totals, map(float, fields), fillvalue=0)] averages = [total/count for total in totals] for print_counter, average in enumerate(averages): print(' {:9.4f}'.format(average)) if print_counter % GROUP_SIZE == 0: file_write.write(str(average)+'\n') file_write.write('\n') file_write.close() mutation_average.close()