If you have a list (from reading the file) in memory, just reformat the list into what you want:
input='''\
2.131583
2.058964
6.866568
0.996470
6.424396
0.996004
6.421990'''
cols=2
data=input.split() # proxy for a file
print data
print '==='
for li in [data[i:i+cols] for i in range(0,len(data),cols)]:
print li
Prints:
['2.131583', '2.058964', '6.866568', '0.996470', '6.424396', '0.996004', '6.421990']
===
['2.131583', '2.058964']
['6.866568', '0.996470']
['6.424396', '0.996004']
['6.421990']
Or, use a N-at-a-time file reading idiom:
import itertools
cols=2
with open('/tmp/nums.txt') as fin:
for li in itertools.izip_longest(*[fin]*cols):
print li
# prints
('2.131583\n', '2.058964\n')
('6.866568\n', '0.996470\n')
('6.424396\n', '0.996004\n')
('6.421990', None)
Which you can combine into one iterator in, one iterator out if you want a type of file filter:
import itertools
cols=2
with open('/tmp/nums.txt') as fin, open('/tmp/nout.txt','w') as fout:
for li in itertools.izip_longest(*[fin]*cols):
fout.write('\t'.join(e.strip() for e in li if e)+'\n')
The output file will now be:
2.131583 2.058964
6.866568 0.996470
6.424396 0.996004
6.421990
If you only want to write the output of there are the full set of numbers, i.e., the remainder numbers at the end of the file that are less than cols
in total length:
import itertools
cols=2
# last number '6.421990' not included since izip is used instead of izip_longest
with open('/tmp/nums.txt') as fin, open('/tmp/nout.txt','w') as fout:
for li in itertools.izip(*[fin]*cols):
fout.write('\t'.join(e.strip() for e in li)+'\n')
Then the output file is:
2.131583 2.058964
6.866568 0.996470
6.424396 0.996004