Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search the word, and replace the whole line containing the word in a file in Python using fileinput

I want to search a particular word in a text file. For each line,where the word is present, I want to completely change the line by a new text.

I want to achieve this using fileinput module of python. There are two observation, I am seeing with following variations :-

Code piece 1 :-

text = "mov9 = "   # if any line contains this text, I want to modify the whole line.
new_text = "mov9 = Alice in Wonderland"
x = fileinput.input(files="C:\Users\Admin\Desktop\DeletedMovies.txt", inplace=1)
for line in x:
    if text in line:
        line = new_text
        print line,
x.close()

The above piece of code wipes out all the content of the file, and writes the new_text i.e. the file content is only

mov9 = Alice in Wonderland

Code Piece 2 :-

text = "mov9 = "   # if any line contains this text, I want to modify the whole line.
new_text = "mov9 = Alice in Wonderland"
x = fileinput.input(files="C:\Users\Admin\Desktop\DeletedMovies.txt", inplace=1)
for line in x:
    if text in line:
        line = line.replace(text, new_text)
        print line,
x.close()

The above piece of code, even though adds the needed line i.e. new_text where text is found, but doesn't deletes the line, but keeps the previous data also.

That is if the line was earlier :-

mov9 = Fast & Furios

after running the above piece of code it becomes :-

mov9 = Alice in WonderlandFast & Furios

And other content of the files remain untouched, not deleted as in code in Code piece 1.

But my goal is to find the word mov9 =, and whatever is present along with it, I want to replace the whole line as mov9 = Alice in Wonderland.

How can I achieve that? Thanks in advance....

like image 435
Pabitra Pati Avatar asked Nov 16 '25 08:11

Pabitra Pati


1 Answers

I realized that I was wrong by just an indentation. In the code piece 1 mentioned in the question, if I am bringing the 'print line,' from the scope of if i.e. if i outdent it, then this is solved...

As this line was inside the scope of if, hence, only this new_text was being written to the file, and other lines were not being written, and hence the file was left with only the new_text. So, the code piece should be as follow :-

text = "mov9 = "   # if any line contains this text, I want to modify the whole line.
new_text = "mov9 = Alice in Wonderland"
x = fileinput.input(files="C:\Users\Admin\Desktop\DeletedMovies.txt", inplace=1)
for line in x:
    if text in line:
        line = new_text
    print line,
x.close()

Also, the second solution given by Rolf of Saxony & the first solution by Padraic Cunningham is somehow similar.

like image 138
Pabitra Pati Avatar answered Nov 18 '25 22:11

Pabitra Pati



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!