You open foo
once, but try to iterate over it four times. By the end of the first reduction, you're at the end of file. Either reopen it:
try:
for ln, k in enumerate(map(float, reductions)):
with open(filename, "r") as f:
for key, group in groupby(f, key=getkey):
outfile[ln].writelines(choose_random(group, fraction=k))
finally:
for f in outfile:
f.close()
or rewind after each reduction:
try:
with open(filename, "r") as f:
for ln, k in enumerate(map(float, reductions)):
for key, group in groupby(f, key=getkey):
outfile[ln].writelines(choose_random(group, fraction=k))
f.seek(0)
finally:
for f in outfile:
f.close()
I'd open both files at one point:
reductions = [0.25, 0.50, 0.75, 1.0]
filename = "foo"
for fraction in reductions:
with open(filename, "r") as f, open('%s-%s' % (fraction, filename), 'w') as outfile:
for key, group in groupby(f, key=getkey):
outfile.writelines(choose_random(group, fraction=fraction))