I want to loop over the contents of a text file and do a search and replace on some lines and write the result back to the file. I could first load the whole file in memory and then write it back, but that probably is not the best way to do it.
What is the best way to do this, within the following code?
f = open(file)
for line in f:
if line.contains('foo'):
newline = line.replace('foo', 'bar')
# how to write this newline back to the file
As lassevk suggests, write out the new file as you go, here is some example code:
The shortest way would probably be to use the fileinput module. For example, the following adds line numbers to a file, in-place:
What happens here is:
print
statements write back into the original filefileinput
has more bells and whistles. For example, it can be used to automatically operate on all files insys.args[1:]
, without your having to iterate over them explicitly. Starting with Python 3.2 it also provides a convenient context manager for use in awith
statement.While
fileinput
is great for throwaway scripts, I would be wary of using it in real code because admittedly it's not very readable or familiar. In real (production) code it's worthwhile to spend just a few more lines of code to make the process explicit and thus make the code readable.There are two options:
if you remove the indent at the like below, it will search and replace in multiple line. See below for example.
This should work: (inplace editing)
Using hamishmcn's answer as a template I was able to search for a line in a file that match my regex and replacing it with empty string.
Create a new file, copy lines from the old to the new, and do the replacing before you write the lines to the new file.