简体   繁体   中英

How insert a string in next line for searched pattern in a file using python?

I have a file with Contents as below:-

He is good at python.
Python is not a language as well as animal.
Look for python near you.
Hello World it's great to be here.

Now, script should search for pattern "python" or "pyt" or "pyth" or "Python" or any regex related to "p/Python". After search of particular word, it should insert new word like "Lion". So output should become like below:-

He is good at python.
Lion
Python is not a language as well as animal.
Lion
Look for python near you.
Lion
Hello World it's great to be here.

How can I do that ?

NOTE:- Till now I wrote code like this:-

def insertAfterText(args):
    file_name = args.insertAfterText[0]
    pattern = args.insertAfterText[1]
    val = args.insertAfterText[2]
    fh = fileinput.input(file_name,inplace=True)
    for line in fh:
        replacement=val+line
        line=re.sub(pattern,replacement,line)
        sys.stdout.write(line)
    fh.close()

You're better off writing a new file, than trying to write into the middle of an existing file.

with open is the best way to open files, since it safely and reliably closes them for you once you're done. Here's a cool way of using with open to open two files at once:

import re

pattern = re.compile(r'pyt', re.IGNORECASE)

filename = 'textfile.txt'
new_filename = 'new_{}'.format(filename)

with open(filename, 'r') as readfile, open(new_filename, 'w+') as writefile:
    for line in readfile:
        writefile.write(line)
        if pattern.search(line):
            writefile.write('Lion\n')

Here, we're opening the existing file, and opening a new file (creating it) to write to. We loop through the input file and simply write each line out to the new file. If a line in the original file contains matches for our regex pattern, we also write Lion\\n (including the newline) after writing the original line.

Read the file into a variable:

with open("textfile") as ff:
  s=ff.read()

Use regex and write the result back:

with open("textfile","w") as ff:
  ff.write(re.sub(r"(?mi)(?=.*python)(.*?$)",r"\1\nLion",s))

    (?mi): m: multiline, i.e. '$' will match end of line;
           i: case insensitiv;
    (?=.*python): lookahead, check for "python";
    Lookahead doesn't step forward in the string, only look ahead, so:
    (.*?$) will match the whole line, 
     which we replace with self '\1' and the other.

Edit: To use from command line insert:

import sys
textfile=sys.argv[1]
pattern=sys.argv[2]
newtext=sys.argv[3]

and replace

r"(?mi)(?=.*python)(.*?$)",r"\1\nLion"

with

fr"(?mi)(?=.*{pattern})(.*?$)",r"\1{newtext}"

and in open() change "textfile" to textfile.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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