Currently I'm using this:
f = open(filename, 'r+')
text = f.read()
text = re.sub('foobar', 'bar', text)
f.seek(0)
f.write(text)
f.close()
But the problem is that the old file is larger than the new file. So I end up with a new file that has a part of the old file on the end of it.
If you don't want to close and reopen the file, to avoid race conditions, you could truncate
it:
f = open(filename, 'r+')
text = f.read()
text = re.sub('foobar', 'bar', text)
f.seek(0)
f.write(text)
f.truncate()
f.close()
The functionality may also be cleaner and safer using with open as
per mVChr's comment, which is will close the handler, even if an error occurs.
with open(filename, 'r+') as f:
text = f.read()
text = re.sub('foobar', 'bar', text)
f.seek(0)
f.write(text)
f.truncate()
Probably it would be easier and neater to close the file after text = re.sub('foobar', 'bar', text)
, re-open it for writing (thus clearing old contents), and write your updated text to it.
The fileinput
module has an inline
mode for writing changes to the file you are processing without using temporary files etc. The module nicely encapsulates the common operation of looping over the lines in a list of files, via an object which transparently keeps track of the file name, line number etc if you should want to inspect them inside the loop.
import fileinput
for line in fileinput.FileInput("file",inplace=1):
if "foobar" in line:
line=line.replace("foobar","bar")
print line
Try writing it in a new file..
f = open(filename, 'r+')
f2= open(filename2,'a+')
text = f.read()
text = re.sub('foobar', 'bar', text)
f.seek(0)
f.close()
f2.write(text)
fw.close()
来源:https://stackoverflow.com/questions/2424000/read-and-overwrite-a-file-in-python