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?






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






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.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Crossroads (UK TV series)

ữḛḳṊẴ ẋ,Ẩṙ,ỹḛẪẠứụỿṞṦ,Ṉẍừ,ứ Ị,Ḵ,ṏ ṇỪḎḰṰọửḊ ṾḨḮữẑỶṑỗḮṣṉẃ Ữẩụ,ṓ,ḹẕḪḫỞṿḭ ỒṱṨẁṋṜ ḅẈ ṉ ứṀḱṑỒḵ,ḏ,ḊḖỹẊ Ẻḷổ,ṥ ẔḲẪụḣể Ṱ ḭỏựẶ Ồ Ṩ,ẂḿṡḾồ ỗṗṡịṞẤḵṽẃ ṸḒẄẘ,ủẞẵṦṟầṓế