Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- num_reads = 7
- with open('data.txt') as read_file:
- with open('new_data.txt', 'w') as write_file:
- while (True):
- lines = []
- try: # expect errors if the number of lines in the file are not a multiplication of num_reads
- for i in range(num_reads):
- lines.append(next(read_file)) # when the file finishes an exception occurs here
- #do sutff with the lines (exactly num_reads number of lines)
- processed = " ".join(list(map(lambda x: x.replace("n", ''), lines)))
- write_file.write(processed + 'n')
- except StopIteration: # here we process the (possibly) insufficent last lines
- #do stuff with the lines (less that num_reads)
- processed = " ".join(list(map(lambda x: x.replace("n", ''), lines)))
- write_file.write(processed + 'n')
- break
- line1
- line2
- line3
- line4
- line5
- line7
- line8
- line9
- line1 line2 line3 line4 line5 line7
- line8 line9
- while (....) {
- foo(7);
- }
- foo(3);
- def read_n_lines(infile, n):
- lines = []
- try:
- for _ in range(n):
- lines.append(next(infile))
- except StopIteration:
- pass
- return lines
- while True:
- lines = read_n_lines(infile, 7)
- if len(lines) == 0:
- break
- process_lines(lines)
Add Comment
Please, Sign In to add comment