简体   繁体   English

Python:在包含模式行的模式后打印x行

[英]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. 如果一行在文件中以数字( xyz )开头,则需要打印(或写入文件)此行以及下一个xyz+1行。
What's the best way to do this? 最好的方法是什么?

So far, I've been able to print the line that starts with an int . 到目前为止,我已经能够打印以int开头的行。 How do I print the next lines? 如何打印下几行?

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? 我怎样才能让它停止跳行?

Use a flag, when you find the line set it to true, then use it to write all future lines: 使用标志,当您发现将其设置为true的行时,然后使用它来写所有以后的行:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM