Pythonic way to overwrite a file

Ben Charrow bcharrow at
Wed Jun 17 14:06:12 EDT 2009

Cameron Pulsford wrote:
> Hey all, hopefully a simple question.
> I'm writing a simple python tool that opens a file, and does something like
> for line in file.readlines():
>     temp.write(line.doStuff())
> However, I want to provide the option do this "in place", as in have the
> destination file be the same as the source file. 

Is loading the whole file into memory an option?  If so, this should work:

filename = "spam.txt"
lines = open(filename).readlines()            # Read
new = [somefunction(line) for line in lines]  # Change
open(filename, 'w').writelines(new)           # Write

If you want to stick with your original approach, but want it to work cross
platform, then I think this is what you want:


More information about the Python-list mailing list