# Read and re-write file with one open?

**URL:** <https://rubytalk.org/t/read-and-re-write-file-with-one-open/53145>\
**Category:** ruby-talk\
**Created:** [30 April 2009 04:27 UTC](https://rubytalk.org/t/read-and-re-write-file-with-one-open/53145 "2009-04-30T04:27:58Z")\
**Posts on this page:** 19\
**Page:** 1

<div class="post-metadata">

**Author:** ![Adam\_Bender](https://avatars.discourse-cdn.com/v4/letter/a/df705f/32.png) [@Adam\_Bender](https://rubytalk.org/u/Adam_Bender)\
**Post date:** [30 April 2009 04:27 UTC](https://rubytalk.org/t/read-and-re-write-file-with-one-open/53145/1 "2009-04-30T04:27:58Z")

</div>

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?

Thanks,

Adam

---

<div class="post-metadata">

**Author:** ![Siddick\_Ebramsha](https://avatars.discourse-cdn.com/v4/letter/s/47e85d/32.png) [@Siddick\_Ebramsha](https://rubytalk.org/u/Siddick_Ebramsha)\
**Post date:** [30 April 2009 04:56 UTC](https://rubytalk.org/t/read-and-re-write-file-with-one-open/53145/2 "2009-04-30T04:56:28Z")

</div>

Instead of using the rewind method, you can use the reopen method to  
open a same file in Write mode.  
Example :-  
&nbsp;&nbsp;file = File.open( "filename", "r" )  
&nbsp;&nbsp;file.reopen( "filename", "w" )

> **···**
>
> --  
> Posted via [http://www.ruby-forum.com/](http://www.ruby-forum.com/).

---

<div class="post-metadata">

**Author:** ![Greg\_Brown1](https://avatars.discourse-cdn.com/v4/letter/g/258eb7/32.png) [@Greg\_Brown1](https://rubytalk.org/u/Greg_Brown1)\
**Post date:** [30 April 2009 05:09 UTC](https://rubytalk.org/t/read-and-re-write-file-with-one-open/53145/3 "2009-04-30T05:09:41Z")

</div>

Yes, but typically this is done by creating a new file and then  
renaming it to replace the old one.

Here's an example from my upcoming book "Ruby Best Practices"[0]. It  
naively strips comments from source files.  
You can modify it to fit your needs.

> **···**
>
> On Thu, Apr 30, 2009 at 12:27 AM, Adam Bender \<abender@gmail.com\> 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?
> 
> ----------
> 
> require "tempfile"  
> require "fileutils"
> 
> temp = Tempfile.new("without\_comments")  
> File.foreach(ARGV[0]) do |line|  
> &nbsp;&nbsp;temp \<\< line unless line =~ /^\s\*#/  
> end  
> temp.close
> 
> FileUtils.cp(ARGV[0],"#{ARGV[0]}.bak") # comment out if you don't want backups.  
> FileUtils.mv(temp.path,ARGV[0])
> 
> ----------
> 
> -greg
> 
> PS: sorry for the shameless book plug, but it really might be helpful  
> for questions like these. 🙂
> 
> [0] [http://rubybestpractices.com](http://rubybestpractices.com)

---

<div class="post-metadata">

**Author:** ![7stud](https://avatars.discourse-cdn.com/v4/letter/7/57b2e6/32.png) [@7stud](https://rubytalk.org/u/7stud)\
**Post date:** [30 April 2009 05:26 UTC](https://rubytalk.org/t/read-and-re-write-file-with-one-open/53145/4 "2009-04-30T05:26:17Z")

</div>

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/\](http://www.ruby-forum.com/%5C).

---

<div class="post-metadata">

**Author:** ![Tim\_R](https://avatars.discourse-cdn.com/v4/letter/t/ecc23a/32.png) [@Tim\_R](https://rubytalk.org/u/Tim_R)\
**Post date:** [1 May 2009 19:00 UTC](https://rubytalk.org/t/read-and-re-write-file-with-one-open/53145/5 "2009-05-01T19:00:12Z")

</div>

> [Note: parts of this message were removed to make it a legal post.]
> 
> 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?
> 
> Thanks,
> 
> Adam

> **···**
>
> On Apr 29, 9:27 pm, Adam Bender \<aben...@gmail.com\> wrote:

---

<div class="post-metadata">

**Author:** ![Tim\_R](https://avatars.discourse-cdn.com/v4/letter/t/ecc23a/32.png) [@Tim\_R](https://rubytalk.org/u/Tim_R)\
**Post date:** [1 May 2009 19:10 UTC](https://rubytalk.org/t/read-and-re-write-file-with-one-open/53145/6 "2009-05-01T19:10:07Z")

</div>

I think File objects have a truncate method you can use after reading  
(f.truncate(0) #the file is now blank) to delete the contents.

file.truncate(integer) =\> 0

Truncates file to at most integer bytes. The file must be opened for  
writing. Not available on all platforms.

&nbsp;&nbsp;&nbsp;f = File.new("out", "w")  
&nbsp;&nbsp;&nbsp;f.syswrite("1234567890") #=\> 10  
&nbsp;&nbsp;&nbsp;f.truncate(5) #=\> 0  
&nbsp;&nbsp;&nbsp;f.close() #=\> nil  
&nbsp;&nbsp;&nbsp;File.size("out") #=\> 5

> **···**
>
> On Apr 29, 9:27 pm, Adam Bender \<aben...@gmail.com\> wrote:
> 
> > [Note: parts of this message were removed to make it a legal post.]
> > 
> > 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?
> > 
> > Thanks,
> > 
> > Adam

---

<div class="post-metadata">

**Author:** ![Adam\_Bender](https://avatars.discourse-cdn.com/v4/letter/a/df705f/32.png) [@Adam\_Bender](https://rubytalk.org/u/Adam_Bender)\
**Post date:** [30 April 2009 07:11 UTC](https://rubytalk.org/t/read-and-re-write-file-with-one-open/53145/7 "2009-04-30T07:11:53Z")

</div>

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

> **···**
>
> On Thu, Apr 30, 2009 at 1:26 AM, 7stud -- \<bbxx789\_05ss@yahoo.com\> 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

---

<div class="post-metadata">

**Author:** ![Robert\_K1](https://yyz1.discourse-cdn.com/flex029/user_avatar/rubytalk.org/robert_k1/32/1830_2.png) [@Robert\_K1](https://rubytalk.org/u/Robert_K1)\
**Post date:** [30 April 2009 09:07 UTC](https://rubytalk.org/t/read-and-re-write-file-with-one-open/53145/8 "2009-04-30T09:07:35Z")

</div>

A variant exploiting Ruby's command line parameters:

11:05:08 Temp$ ruby -e '10.times {|i| puts i}' \>| x  
11:05:22 Temp$ cat x  
0  
1  
2  
3  
4  
5  
6  
7  
8  
9  
11:05:23 Temp$ ./x.rb x  
11:05:29 Temp$ cat x  
\<\<\<0\>\>\>  
\<\<\<1\>\>\>  
\<\<\<2\>\>\>  
\<\<\<3\>\>\>  
\<\<\<4\>\>\>  
\<\<\<5\>\>\>  
\<\<\<6\>\>\>  
\<\<\<7\>\>\>  
\<\<\<8\>\>\>  
\<\<\<9\>\>\>  
11:05:34 Temp$ cat x.bak  
0  
1  
2  
3  
4  
5  
6  
7  
8  
9  
11:05:37 Temp$ cat x.rb  
#!/opt/bin/ruby19 -pi.bak

$\_.sub! /^/, '\<\<\<'  
$\_.sub! /$/, '\>\>\>'  
11:05:40 Temp$

Kind regards

robert

> **···**
>
> 2009/4/30 Gregory Brown \<gregory.t.brown@gmail.com\>:
> 
> > On Thu, Apr 30, 2009 at 12:27 AM, Adam Bender \<abender@gmail.com\> 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, but typically this is done by creating a new file and then  
> > renaming it to replace the old one.
> > 
> > Here's an example from my upcoming book "Ruby Best Practices"[0]. It  
> > naively strips comments from source files.
> 
> --  
> remember.guy do |as, often| as.you\_can - without end  
> [http://blog.rubybestpractices.com/](http://blog.rubybestpractices.com/)

---

<div class="post-metadata">

**Author:** ![James\_Dinkel1](https://avatars.discourse-cdn.com/v4/letter/j/ecc23a/32.png) [@James\_Dinkel1](https://rubytalk.org/u/James_Dinkel1)\
**Post date:** [30 April 2009 14:41 UTC](https://rubytalk.org/t/read-and-re-write-file-with-one-open/53145/9 "2009-04-30T14:41:26Z")

</div>

Gregory Brown wrote:

> Here's an example from my upcoming book "Ruby Best Practices"[0]. It  
> naively strips comments from source files.  
> You can modify it to fit your needs.
> 
> ----------
> 
> require "tempfile"  
> require "fileutils"
> 
> temp = Tempfile.new("without\_comments")  
> File.foreach(ARGV[0]) do |line|  
> &nbsp;&nbsp;temp \<\< line unless line =~ /^\s\*#/  
> end  
> temp.close
> 
> FileUtils.cp(ARGV[0],"#{ARGV[0]}.bak") # comment out if you don't want  
> backups.  
> FileUtils.mv(temp.path,ARGV[0])
> 
> ----------
> 
> -greg

What about if another program opens the file after it has been read by  
the Ruby program but before the Ruby program has copied the temp file?  
If the second program makes a change and saves it, those changes will be  
lost when the Ruby program copies the temp file over it. Or if the  
second program still has it open and the Ruby program finishes, then  
when the second program saves it's open file, it will overwrite the Ruby  
program's changes.

> **···**
>
> --  
> Posted via [http://www.ruby-forum.com/\](http://www.ruby-forum.com/%5C).

---

<div class="post-metadata">

**Author:** ![James\_Dinkel1](https://avatars.discourse-cdn.com/v4/letter/j/ecc23a/32.png) [@James\_Dinkel1](https://rubytalk.org/u/James_Dinkel1)\
**Post date:** [1 May 2009 20:33 UTC](https://rubytalk.org/t/read-and-re-write-file-with-one-open/53145/10 "2009-05-01T20:33:36Z")

</div>

timr wrote:

> Truncates file to at most integer bytes. The file must be opened for  
> writing. Not available on all platforms.
> 
> &nbsp;&nbsp;&nbsp;f = File.new("out", "w")  
> &nbsp;&nbsp;&nbsp;f.syswrite("1234567890") #=\> 10  
> &nbsp;&nbsp;&nbsp;f.truncate(5) #=\> 0  
> &nbsp;&nbsp;&nbsp;f.close() #=\> nil  
> &nbsp;&nbsp;&nbsp;File.size("out") #=\> 5

That's pretty close to how I've been modifying files:

&nbsp;&nbsp;File.open(filename, 'r+') do |file|  
&nbsp;&nbsp;&nbsp;&nbsp;lines = file.readlines

&nbsp;&nbsp;&nbsp;&nbsp;# modify data in the lines array

&nbsp;&nbsp;&nbsp;&nbsp;file.pos = 0  
&nbsp;&nbsp;&nbsp;&nbsp;file.print lines # will not put \$ between array elements  
&nbsp;&nbsp;&nbsp;&nbsp;file.truncate(file.pos)  
&nbsp;&nbsp;end

This opens a file for reading and writing, reads the file into an array,  
then you modify the array how you need to. Then the block returns to  
the beginning of the file, writes out your changes over the existing  
file, then chops off what's left. Then, of course, the file is closed  
when the block exits.

To get a little more complicated, I wrapped this in a class method:

class File

&nbsp;&nbsp;def self.change!(filename, create = false)  
&nbsp;&nbsp;&nbsp;&nbsp;### method to make it easy to open a file and make changes to it.  
&nbsp;&nbsp;&nbsp;&nbsp;### usage example  
&nbsp;&nbsp;&nbsp;&nbsp;## File.change(myfile) do |contents|  
&nbsp;&nbsp;&nbsp;&nbsp;## contents.gsub!(/this/, "that")  
&nbsp;&nbsp;&nbsp;&nbsp;## end  
&nbsp;&nbsp;&nbsp;&nbsp;### I can also use "throw(:nochanges)" anywhere in the block  
&nbsp;&nbsp;&nbsp;&nbsp;### to prevent the file from being written.  
&nbsp;&nbsp;&nbsp;&nbsp;### Make sure 'contents' does not get pointed to a new object;  
&nbsp;&nbsp;&nbsp;&nbsp;### for example, an assignemt "contents = 'new data'" will break the  
method

&nbsp;&nbsp;&nbsp;&nbsp;# if create is true, create the file if it does not exist  
&nbsp;&nbsp;&nbsp;&nbsp;if create == true  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;File.open(filename, 'w') { |blank| blank.write '' } unless  
File.exist?(filename)  
&nbsp;&nbsp;&nbsp;&nbsp;end

&nbsp;&nbsp;&nbsp;&nbsp;# read the file, execute a block, then write the file  
&nbsp;&nbsp;&nbsp;&nbsp;if File.exist?(filename)  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;File.open(filename, 'r+') do |file|  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;lines = file.readlines  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;# do not write the file if it did not change (block must "throw  
:nochanges")  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;catch(:nochanges) do  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;yield lines  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;file.pos = 0  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;file.print lines # will not put \$ between array elements  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;file.truncate(file.pos)  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;end  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;end  
&nbsp;&nbsp;&nbsp;&nbsp;end  
&nbsp;&nbsp;end  
end

> **···**
>
> > On Apr 29, 9:27�pm, Adam Bender \<aben...@gmail.com\> wrote:
> 
> --  
> Posted via [http://www.ruby-forum.com/\](http://www.ruby-forum.com/%5C).

---

<div class="post-metadata">

**Author:** ![7stud](https://avatars.discourse-cdn.com/v4/letter/7/57b2e6/32.png) [@7stud](https://rubytalk.org/u/7stud)\
**Post date:** [30 April 2009 07:54 UTC](https://rubytalk.org/t/read-and-re-write-file-with-one-open/53145/11 "2009-04-30T07:54:38Z")

</div>

Adam Bender wrote:

> > 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).

Of course, if that was a possibility then you would take extra measures  
like create a new file name with rand, and then check it with  
File.exists?, which is probably what Tempfile does.

> Does Tempfile guarantee that it won't overwrite an

existing file?

What the standard library docs aren't clear enough for you:

> **···**
>
> > On Thu, Apr 30, 2009 at 1:26 AM, 7stud -- \<bbxx789\_05ss@yahoo.com\> \> wrote:
> 
> ----  
> tempfile - manipulates temporary files  
> ----
> 
> ???!! lol. pathetic. But once in a great while you can actually find  
> some information on a standard library module using google:
> 
> [http://www.rubytips.org/2008/01/11/using-temporary-files-in-ruby-tempfilenew/](http://www.rubytips.org/2008/01/11/using-temporary-files-in-ruby-tempfilenew/)
> 
> --  
> Posted via [http://www.ruby-forum.com/\](http://www.ruby-forum.com/%5C).

---

<div class="post-metadata">

**Author:** ![Greg\_Brown1](https://avatars.discourse-cdn.com/v4/letter/g/258eb7/32.png) [@Greg\_Brown1](https://rubytalk.org/u/Greg_Brown1)\
**Post date:** [30 April 2009 13:58 UTC](https://rubytalk.org/t/read-and-re-write-file-with-one-open/53145/12 "2009-04-30T13:58:40Z")

</div>

Yes, Tempfile avoids file collisions.

-greg

> **···**
>
> On Thu, Apr 30, 2009 at 3:11 AM, Adam Bender \<abender@gmail.com\> wrote:
> 
> > 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?

---

<div class="post-metadata">

**Author:** ![Greg\_Brown1](https://avatars.discourse-cdn.com/v4/letter/g/258eb7/32.png) [@Greg\_Brown1](https://rubytalk.org/u/Greg_Brown1)\
**Post date:** [30 April 2009 14:53 UTC](https://rubytalk.org/t/read-and-re-write-file-with-one-open/53145/13 "2009-04-30T14:53:52Z")

</div>

Is this related to the OP's concerns? In this case, you'd need file  
locking (see the Ruby API).  
But I didn't see any mention of these sorts of issues in Adam's original post.

If you need this feature, read the API docs for File#flock

-greg

> **···**
>
> On Thu, Apr 30, 2009 at 10:41 AM, James Dinkel \<jdinkel@gmail.com\> wrote:
> 
> > What about if another program opens the file after it has been read by  
> > the Ruby program but before the Ruby program has copied the temp file?  
> > If the second program makes a change and saves it, those changes will be  
> > lost when the Ruby program copies the temp file over it. Or if the  
> > second program still has it open and the Ruby program finishes, then  
> > when the second program saves it's open file, it will overwrite the Ruby  
> > program's changes.

---

<div class="post-metadata">

**Author:** ![James\_Dinkel1](https://avatars.discourse-cdn.com/v4/letter/j/ecc23a/32.png) [@James\_Dinkel1](https://rubytalk.org/u/James_Dinkel1)\
**Post date:** [1 May 2009 20:39 UTC](https://rubytalk.org/t/read-and-re-write-file-with-one-open/53145/14 "2009-05-01T20:39:57Z")

</div>

Aw, word wrapping broke some of my lines...

these should be single lines:

> **···**
>
> > ### for example, an assignemt "contents = 'new data'" will break the method
> 
> > File.open(filename, 'w') { |blank| blank.write '' } unless File.exist?(filename)
> 
> > # do not write the file if it did not change (block must "throw :nochanges")
> 
> --  
> Posted via [http://www.ruby-forum.com/\](http://www.ruby-forum.com/%5C).

---

<div class="post-metadata">

**Author:** ![Adam\_Bender](https://avatars.discourse-cdn.com/v4/letter/a/df705f/32.png) [@Adam\_Bender](https://rubytalk.org/u/Adam_Bender)\
**Post date:** [1 May 2009 23:49 UTC](https://rubytalk.org/t/read-and-re-write-file-with-one-open/53145/15 "2009-05-01T23:49:02Z")

</div>

This is exactly what I wanted. Thanks everyone.

Adam

> **···**
>
> On Fri, May 1, 2009 at 4:33 PM, James Dinkel \<jdinkel@gmail.com\> wrote:
> 
> > That's pretty close to how I've been modifying files:
> > 
> > File.open(filename, 'r+') do |file|  
> > &nbsp;&nbsp;&nbsp;lines = file.readlines
> > 
> > &nbsp;&nbsp;&nbsp;# modify data in the lines array
> > 
> > &nbsp;&nbsp;&nbsp;file.pos = 0  
> > &nbsp;&nbsp;&nbsp;file.print lines # will not put \$ between array elements  
> > &nbsp;&nbsp;&nbsp;file.truncate(file.pos)  
> > end
> > 
> > This opens a file for reading and writing, reads the file into an array,  
> > then you modify the array how you need to. Then the block returns to  
> > the beginning of the file, writes out your changes over the existing  
> > file, then chops off what's left. Then, of course, the file is closed  
> > when the block exits.

---

<div class="post-metadata">

**Author:** ![Martin\_DeMello](https://avatars.discourse-cdn.com/v4/letter/m/f17d59/32.png) [@Martin\_DeMello](https://rubytalk.org/u/Martin_DeMello)\
**Post date:** [1 May 2009 19:18 UTC](https://rubytalk.org/t/read-and-re-write-file-with-one-open/53145/16 "2009-05-01T19:18:07Z")

</div>

Don't just scoff, send in a patch!

martin

> **···**
>
> On Thu, Apr 30, 2009 at 1:24 PM, 7stud -- \<bbxx789\_05ss@yahoo.com\> wrote:
> 
> > What the standard library docs aren't clear enough for you:
> > 
> > ----  
> > tempfile - manipulates temporary files  
> > ----
> > 
> > ???!! lol. pathetic.

---

<div class="post-metadata">

**Author:** ![7stud](https://avatars.discourse-cdn.com/v4/letter/7/57b2e6/32.png) [@7stud](https://rubytalk.org/u/7stud)\
**Post date:** [2 May 2009 08:05 UTC](https://rubytalk.org/t/read-and-re-write-file-with-one-open/53145/17 "2009-05-02T08:05:11Z")

</div>

Adam Bender wrote:

> > end
> > 
> > This opens a file for reading and writing, reads the file into an array,  
> > then you modify the array how you need to. Then the block returns to  
> > the beginning of the file, writes out your changes over the existing  
> > file, then chops off what's left. Then, of course, the file is closed  
> > when the block exits.
> 
> This is exactly what I wanted. Thanks everyone.
> 
> Adam

I think you guys are missing the point. There are lots of ways to  
rewrite a file that 'work'. For instance, simply reading a file into an  
array, closing the file, then opening the file for writing(which erases  
the file), and then writing the altered lines back to the file 'works'.  
You can test it yourself and see that it works. You can rewrite the  
file like that 1,000 times and it will 'work'.

However, if your data is important you need to ask yourself the  
question: what happens if my program crashes while I am writing the data  
back out to the file?

So let's ask that question about the solution you've decided to adopt.  
Suppose your program is at the point where it has written half of the  
altered data back to the file, and the file contains half altered data  
and half original data. Then your program crashes. What are you left  
with?

The "rewriting a file" issue has been hashed out by many programmers for  
decades. You can either try to come up with your own screwy method, or  
you can adopt an accepted idiom. Within the accepted idiom, modules  
like Tempfile were created to deal with the problem of overwriting an  
existing file name, and it provides a shortcut.

> truncate: Not available on all platforms.

That should also be a red flag. Generally, you should strive to write  
cross platform programs.

> **···**
>
> > On Fri, May 1, 2009 at 4:33 PM, James Dinkel \<jdinkel@gmail.com\> wrote:
> 
> --  
> Posted via [http://www.ruby-forum.com/\](http://www.ruby-forum.com/%5C).

---

<div class="post-metadata">

**Author:** ![7stud](https://avatars.discourse-cdn.com/v4/letter/7/57b2e6/32.png) [@7stud](https://rubytalk.org/u/7stud)\
**Post date:** [2 May 2009 08:29 UTC](https://rubytalk.org/t/read-and-re-write-file-with-one-open/53145/18 "2009-05-02T08:29:21Z")

</div>

7stud -- wrote:

> Adam Bender wrote:
> 
> > > end
> > > 
> > > This opens a file for reading and writing, reads the file into an array,  
> > > then you modify the array how you need to. Then the block returns to  
> > > the beginning of the file, writes out your changes over the existing  
> > > file, then chops off what's left. Then, of course, the file is closed  
> > > when the block exits.
> > 
> > This is exactly what I wanted. Thanks everyone.
> > 
> > Adam
> 
> I think you guys are missing the point. There are lots of ways to  
> rewrite a file that 'work'. For instance, simply reading a file into an  
> array, closing the file, then opening the file for writing(which erases  
> the file), and then writing the altered lines back to the file 'works'.  
> You can test it yourself and see that it works. You can rewrite the  
> file like that 1,000 times and it will 'work'.
> 
> However, if your data is important you need to ask yourself the  
> question: what happens if my program crashes while I am writing the data  
> back out to the file?
> 
> So let's ask that question about the solution you've decided to adopt.  
> Suppose your program is at the point where it has written half of the  
> altered data back to the file, and the file contains half altered data  
> and half original data. Then your program crashes. What are you left  
> with?

Hmmm...I guess you are left with a file that you can examine and then  
locate the spot where you should begin gsub'ing again.

You may however run into a problem if the program crashes in the middle  
of a line. Input and output to/from files gets buffered to make things  
more efficient because repeatedly accessing files is relatively slow.  
For instance, when you tell your program to write a line to a file, it  
doesn't actually do that. Instead, programs store the line in a buffer.  
Then when the buffer fills up, the contents of the buffer get written to  
the file in one big chunk. That cuts down on the number of file  
accesses. The same thing happens when you read from a file. You may  
tell your program to read one line from a file, but your program will  
ignore you. Instead, your program will read a chunk of the file and  
store it in a buffer. Then If you request more lines from the file,  
your program will retrieve them from the buffer. That cuts down on the  
number of times your program has to access the file.

As a result, I think even though you may write one line at a time to the  
file, it's possible the buffer may get written to the file where the  
last thing in the buffer is half a line. Then if your program crashes  
you are going to have a corrupted line in your file.

> **···**
>
> > > On Fri, May 1, 2009 at 4:33 PM, James Dinkel \<jdinkel@gmail.com\> wrote:
> 
> --  
> Posted via [http://www.ruby-forum.com/\](http://www.ruby-forum.com/%5C).

---

<div class="post-metadata">

**Author:** ![Greg\_Brown1](https://avatars.discourse-cdn.com/v4/letter/g/258eb7/32.png) [@Greg\_Brown1](https://rubytalk.org/u/Greg_Brown1)\
**Post date:** [2 May 2009 18:57 UTC](https://rubytalk.org/t/read-and-re-write-file-with-one-open/53145/19 "2009-05-02T18:57:45Z")

</div>

Thanks for going into the detail here. I threw the atomic save  
solution out there, but didn't give much background, and this  
establishes a much better motivation for it.

-greg

> **···**
>
> On Sat, May 2, 2009 at 4:05 AM, 7stud -- \<bbxx789\_05ss@yahoo.com\> wrote:
> 
> > So let's ask that question about the solution you've decided to adopt.  
> > Suppose your program is at the point where it has written half of the  
> > altered data back to the file, and the file contains half altered data  
> > and half original data. Then your program crashes. What are you left  
> > with?
> > 
> > The "rewriting a file" issue has been hashed out by many programmers for  
> > decades. You can either try to come up with your own screwy method, or  
> > you can adopt an accepted idiom. Within the accepted idiom, modules  
> > like Tempfile were created to deal with the problem of overwriting an  
> > existing file name, and it provides a shortcut.
