Guest User

Untitled

a guest
Jan 18th, 2019
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.40 KB | None | 0 0
  1. num_reads = 7
  2. with open('data.txt') as read_file:
  3. with open('new_data.txt', 'w') as write_file:
  4.  
  5. while (True):
  6. lines = []
  7. try: # expect errors if the number of lines in the file are not a multiplication of num_reads
  8. for i in range(num_reads):
  9. lines.append(next(read_file)) # when the file finishes an exception occurs here
  10.  
  11. #do sutff with the lines (exactly num_reads number of lines)
  12. processed = " ".join(list(map(lambda x: x.replace("n", ''), lines)))
  13. write_file.write(processed + 'n')
  14.  
  15. except StopIteration: # here we process the (possibly) insufficent last lines
  16. #do stuff with the lines (less that num_reads)
  17. processed = " ".join(list(map(lambda x: x.replace("n", ''), lines)))
  18. write_file.write(processed + 'n')
  19. break
  20.  
  21. line1
  22. line2
  23. line3
  24. line4
  25. line5
  26. line7
  27. line8
  28. line9
  29.  
  30. line1 line2 line3 line4 line5 line7
  31. line8 line9
  32.  
  33. while (....) {
  34. foo(7);
  35. }
  36. foo(3);
  37.  
  38. def read_n_lines(infile, n):
  39. lines = []
  40. try:
  41. for _ in range(n):
  42. lines.append(next(infile))
  43. except StopIteration:
  44. pass
  45. return lines
  46.  
  47. while True:
  48. lines = read_n_lines(infile, 7)
  49. if len(lines) == 0:
  50. break
  51. process_lines(lines)
Add Comment
Please, Sign In to add comment