Your code has multiple issues;
- When you read a line from a file handle, you consume it; it cannot be read again (unless you close and reopen the file handle, or rewind it). See e.g. Why can't I call read() twice on an open file?
- Your code would repeat the lines next to each other. If you managed to sort out the previous bug, you would get repeated
Line 1
followed by repeated Line 2
etc. By your example, you want to repeat the entire block k
times, in the same sequence.
enumerate
starts its numbering at 0; you can switch to 1-based indexing (or generally any base number) by passing an additional parameter.
Here's an attempt to rectify these bugs. For simplicity, this is just reading standard input and writing to standard output. (This is actually a useful convention because this way, you can use it on any file, without needing to hard-code anything or parse the command line.)
import sys
lines_to_repeat = [5, 6, 7]
memory = []
for i, line in enumerate(sys.stdin, 1):
if i in lines_to_repeat:
memory.append(line)
elif memory:
sys.stdout.write(''.join(memory))
memory = []
sys.stdout.write(line)
If you want to repeat more than once, you can add a loop in the elif memory:
block, or just multiply the join
ed string with the number of additional repeats (in Python, 3 * "abc"
evaluates to "abcabcabc"
).
Demo: https://ideone.com/LGOBHX
An organizing assumption is that you want a single block of contiguous lines to be repeated; if you want to repeat multiple disparate blocks, that will take some rather heavy refactoring. (Probably ask a new question with your real requirements then.)