[Tutor] loop print issue
Mats Wichmann
mats at wichmann.us
Fri Oct 11 12:50:18 EDT 2019
On 10/11/19 9:32 AM, Alan Gauld via Tutor wrote:
> You are using counters so you are writing the first 36 lines(0-35)
> to output1. Then you write the rest to output2. If that is what
> you want it would be a lot easier to say so explicitly:
>
> with open('output1.txt','w') as output1
> for count in range(36):
> output1.write(xlist_file.readline())
>
> with open('output2.txt','w') as output2:
> for line in xlist_file:
> output2 write(line)
>
> No need for resetting sys.stdout.
> No need for fancy '+' modes.
> No need for complex counters or if statements.
Just for grins, here's another way to implement the idiom of splitting a
list into chunks:
import itertools
with open('output1.txt', 'w') as output1:
output1.writelines(itertools.islice(xlist_file, 36))
with open('output2.txt', 'w') as output2:
# previous islice has "consumed" the 36 lines, continue to end
output2.writelines(itertools.islice(xlist_file, None))
More information about the Tutor
mailing list