Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String replacement on a whole text file in Python 3.x?

How can I replace a string with another string, within a given text file. Do I just loop through readline() and run the replacement while saving out to a new file? Or is there a better way?

I'm thinking that I could read the whole thing into memory, but I'm looking for a more elegant solution...

Thanks in advance

like image 628
John B Avatar asked Jun 02 '10 20:06

John B


People also ask

How do you replace text in a text file in Python?

To replace text in a file we are going to open the file in read-only using the open() function. Then we will t=read and replace the content in the text file using the read() and replace() functions.

Can you replace multiple strings in Python?

01) Using replace() method Python offers replace() method to deal with replacing characters (single or multiple) in a string. The replace method returns a new object (string) replacing specified fields (characters) with new values.

How do I replace text in all files?

Remove all the files you don't want to edit by selecting them and pressing DEL, then right-click the remaining files and choose Open all. Now go to Search > Replace or press CTRL+H, which will launch the Replace menu. Here you'll find an option to Replace All in All Opened Documents.


1 Answers

fileinput is the module from the Python standard library that supports "what looks like in-place updating of text files" as well as various other related tasks.

for line in fileinput.input(['thefile.txt'], inplace=True):
    print(line.replace('old stuff', 'shiny new stuff'), end='')

This code is all you need for the specific task you mentioned -- it deals with all of the issues (writing to a different file, removing the old one when done and replacing it with the new one). You can also add a further parameter such as backup='.bk' to automatically preserve the old file as (in this case) thefile.txt.bk, as well as process multiple files, take the filenames to process from the commandline, etc, etc -- do read the docs, they're quite good (and so is the module I'm suggesting!-).

like image 161
Alex Martelli Avatar answered Sep 24 '22 02:09

Alex Martelli