From: Adam Bender Date: 2009-04-30T16:11:53+09:00 Subject: Re: Read and re-write file with one open? --0016e6dd8d7ef52a220468c0682a Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: 7bit On Thu, Apr 30, 2009 at 1:26 AM, 7stud -- wrote: > Yes, opening the file in write mode! However, you are going to expose > yourself to this catastrophe. Suppose you read the contents of the > file into a variable, then open the file for writing, which then erases > the file, but immediately thereafter your program crashes or the power > goes out in your city. > > So the idiom for rewriting a file is: > > 1) Open the file for *reading*. > 2) Open another file for writing with a name like origName-edited.txt > 3) Read the original file line by line(saves memory, but is slower) > 4) Write each altered line to the file origName-edited.txt > 5) Delete the original file. > 6) Change the name of the new file (origName-edited.txt) to origName.txt I see the potential for catastrophe with the way I suggested, however, there is potential for catastrophe here if there is already an "origName-edited.txt" file (I know, slim chance, but you never know). You could get around this by generating new file names until you found one that didn't exist, or writing to /tmp, of course. I think I'll switch to Greg Brown's suggestion. Does Tempfile guarantee that it won't overwrite an existing file? Adam --0016e6dd8d7ef52a220468c0682a--