String replacement on a whole text file in Python 3.x?
Question:
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
Answers:
If the file can be read into memory at once, I’d say that
old = myfile.read()
new = old.replace("find this", "replace by this")
output.write(new)
is at least as readable as
for line in myfile:
output.write(line.replace("find this", "replace by this"))
and it might be a little faster, but in the end it probably doesn’t really matter.
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!-).
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
If the file can be read into memory at once, I’d say that
old = myfile.read()
new = old.replace("find this", "replace by this")
output.write(new)
is at least as readable as
for line in myfile:
output.write(line.replace("find this", "replace by this"))
and it might be a little faster, but in the end it probably doesn’t really matter.
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!-).