2

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()

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @daveruinseverything , it's a good solution and serves the purpose but I want to make changes in original file only how can I do that? Moreover, how to take inputs argument for regex 'pyt'
1

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.

1 Comment

thanks it seems to be working but can you make it a command line? like I have to give - python abc.py filename pattern newtext

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.