# Reading and Writing to Tempfile

**URL:** <https://www.ruby-forum.com/t/reading-and-writing-to-tempfile/175853>\
**Category:** Ruby\
**Created:** [September 21, 2009, 4:15pm UTC](https://www.ruby-forum.com/t/reading-and-writing-to-tempfile/175853 "2009-09-21T16:15:42Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![brad](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/59ef9b/32.png) [@brad](https://www.ruby-forum.com/u/brad)\
**Post date:** [September 21, 2009, 4:15pm UTC](https://www.ruby-forum.com/t/reading-and-writing-to-tempfile/175853/1 "2009-09-21T16:15:42Z")

</div>

Hello,

I’m having a hard time getting tempfile to work correctly for me. I  
have a couple of questions

Isn’t it possible to open a tempfile, write to it, close it then later  
open it again write to it and close it?  
I don’t seem to be able to do that. Every time I write to the file it  
only or over writes what is in the file.

require ‘tempfile’

temp = Tempfile.new(“stuff”)  
name = temp.path  
temp.puts “I was here”  
temp.close

# here I’d like to reopen the file and write another line

#later  
temp.open  
str = temp.gets # I was here

temp.close(true)

What am I doing wrong?

Any help is good, thank you.

Tex

---

<div class="post-metadata">

**Author:** ![brad](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/59ef9b/32.png) [@brad](https://www.ruby-forum.com/u/brad)\
**Post date:** [September 21, 2009, 8:18pm UTC](https://www.ruby-forum.com/t/reading-and-writing-to-tempfile/175853/2 "2009-09-21T20:18:43Z")

</div>

On Sep 21, 2009, at 6:35 AM, Brad wrote:

> Hello,
> 
> I’m having a hard time getting tempfile to work correctly for me. I  
> have a couple of questions
> 
> Isn’t it possible to open a tempfile, write to it, close it then later  
> open it again write to it and close it?

Check the documentation on IO (I know, I know…the class is “File”  
but all the important documentation is under “IO”). Specifically, you  
want to set the mode on the file to “a” instead of just “w” when you  
open it.

- Josh
