Personally, I would do this kind of thing line by line. I don't like the idea of putting my entire file into memory, then overwriting it. What if something goes wrong in between? Basically I don't trust myself to write good code!
So, looping through line by line, I would write to a new file with any changes. In Python, you can open two files at once, which is perfect for reading from one and writing to another.
Applying PEP8 for naming, you'd end up with something like this:
def file_search_replace(open_file, search, replacement):
with open(open_file, 'r') as read_file, open('new_file.txt', 'w+') as write_file:
for line in read_file:
write_file.write(line.replace(search, replacement))
I've changed a few of the names, notably replace
to replacement
so it's clear it's not the same as replace()
.
Finally, if you're happy with the result, you can easily rename the file to something else. Personally I'd keep the old one just in case.