From: 7stud -- Date: 2009-04-30T14:26:17+09:00 Subject: Re: Read and re-write file with one open? Adam Bender wrote: > I would like to write a Ruby script that opens a text file, performs a > gsub > on each line, and then overwrites the file with the updated contents. > Right > now I open the file twice: once to read and once to write. The reason > for > this is that if I try to perform both operations on the same IO object > by > calling io.rewind and writing from the beginning, and the substituted > word > is shorter than what it is replacing, some portion of the end of the > original file remains. Is there an idiom for "clearing" the contents of > the > file before writing? > 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. What are you left with? You will be left with an empty file, and the variable that contained the contents of the file will have evaporated into the ether. In other words, you will lose all your data! 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 -- Posted via http://www.ruby-forum.com/.