Python to insert a line at a random location of a large text file with condition -


i have 30000 plus line text file need modify using python. want following:

  1. there specific keyword1 in file has device name following keyword1. need identify keyword1 in lines , retrieve device names, store them in list later use

    i have achieved using regular expression

  2. once have device names list, need insert newline "fixed format + device name" file @ series of specific locations following keyword2

    this run problem.

    originally used simple counting method. pattern.search(line) throughout file , once keyword1 identified, locate inserting location counting + 5, index of line keyword1 identified. however, turns out line order in file matter need insert newline after line keyword2 located. what's more troublesome keyword2 exists everywhere in file. keyword2 within 7 lines after keyword1 needs considered.

to give example:

 random line keyword2      <--- keyword2 not considered  random line  random line  random line, keyboard1 "device name"     <--- id keyword1 , record device  random line  random line  random line  random line  random line keyword2      <--- keyword2 considered 

any suggestion appreciated. in advance

i ... think should approach this:

with open('input.txt') fhi, open('output.txt', 'w') fho:   line in fhi:     if not pattern.search(line):       # if there no match write line output file , proceed.       fho.write(line)       continue      # if far found match.  scan 7 lines.     in range(7):       tocheck = next(fhi)        if not pattern2.search(tocheck):         # if don't find 2nd keyword write line, continue sub-loop.         fho.write(tocheck)         continue        # if far found second pattern.  add our newline.       fho.write(tocheck)       fho.write('\r\n') 

this using multiple-file syntax introduced in 2.7. in earlier versions you'll have nest statements or manage file handles manually.


Comments

Popular posts from this blog

linux - Using a Cron Job to check if my mod_wsgi / apache server is running and restart -

actionscript 3 - TweenLite does not work with object -

jQuery Ajax Render Fragments OR Whole Page -