Python: Print x lines after a pattern including the line with pattern
Python: Print x lines after a pattern including the line with pattern
If a line starts with a number(xyz
) in a file, I need to print(or write to a file) this line and the next xyz+1
lines.
What's the best way to do this?
xyz
xyz+1
So far, I've been able to print the line that starts with an int
. How do I print the next lines?
int
import glob, os, sys
import subprocess
file = 'filename.txt'
with open(file,'r') as f:
data = f.readlines()
for line in data:
if line[0].isdigit():
print int(line)
If I made an iterator out of data
, the print function skips a line every time.
data
with open(file,'r') as f:
data = f.readlines()
x = iter(data)
for line in x:
if line[0].isdigit():
print int(line)
for i in range(int(line)):
print x.next()
How could I make it stop skipping lines?
Welcome to SO. Please take the time to read How to Ask and the other links found on that page. Voting to close as : Too Broad.
– wwii
Sep 11 '18 at 19:05
@lkriener have a look
– nac001
Sep 11 '18 at 19:34
Can you assume that nothing except for the number
xyz
is written in a line? Otherwise the int(line)
you use multiple times will fail.– lkriener
Sep 11 '18 at 21:10
xyz
int(line)
1 Answer
1
Use a flag, when you find the line set it to true, then use it to write all future lines:
can_write = False
with open('source.txt') as f, open('destination.txt', 'w') as fw:
for line in f:
if line.startswith(xyz):
can_write = True
if can_write:
fw.write(line)
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
What have you tried so far? We are here to help when you are stuck, not to just write the whole code for you...
– lkriener
Sep 11 '18 at 19:01