Pythonic way to overwrite a file
bcharrow at csail.mit.edu
Wed Jun 17 20:06:12 CEST 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():
> 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