Reading and overwriting a file in Python

I am currently 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 bigger than the new one. This way I get a new file that has part of the old file at the end.

+80
python overwrite file
Mar 11 '10 at 10:01
source share
4 answers

If you do not want to close and reopen the file to avoid race conditions, you can truncate :

 f = open(filename, 'r+') text = f.read() text = re.sub('foobar', 'bar', text) f.seek(0) f.write(text) f.truncate() f.close() 

Functionality can also be cleaner and safer using with open as for the mVChr comment, which closes 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() 
+135
Mar 11 '10 at 11:16
source share

It would probably be easier and more accurate to close the file after text = re.sub('foobar', 'bar', text) , re-open it for writing (thereby clearing the old contents) and write your updated text into it.

+14
Mar 11
source share

The fileinput module has inline mode for recording changes to the file you are processing, without using temporary files, etc. The module perfectly encapsulates the general operation of looping through the lines in the file list through an object that transparently tracks the file name, line number, etc., if you want to check 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 
+14
Mar 11 '10 at 10:08
source share

Try writing it to 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() 
-2
Jun 29 '16 at 11:59
source share



All Articles