From: Robert Klemme Date: 2007-08-24T21:01:49+09:00 Subject: Re: How to append some data at the beginning of a file 2007/8/24, Uday Thokala : > Ronald Fischer wrote: > >> I am newbie to Ruby so please spare me if the question looks silly. My > >> question is how to append data at the beginning of a file? > > > > This is not so much a Ruby question, since nearly no operating system > > directly > > allows appending data to the beginning of a file. > > Thanks Ronald for your comments. I am wondering may be ruby got some way > around it. > > > The general solution > > is to create a new file, putting there the data in the right order, > > delete > > the old file and rename the new file to the name of the old one. > > > > Renaming a file is done like this: > > > > File.rename("oldname","newname") > > Yeah I implemented the above mentioned solution and it's working fine. > The code is > > newfile = File.new("test1","w") > newfile.puts "This line should appear at the top of each file"; > > oldfile = File.open("test", "r+") > oldfile.each_line { |line| newfile.puts line} > > oldfile.close(); > newfile.close(); > > File.delete("test"); > File.rename("test1", "test"); Just a few remarks: better return to your old habit and use the block form of File.open (btw, you do not need to close the file, File#open takes care of that when the block is left - even in case of an exception). You don't need to terminate lines with ";". Also, you can use variables to make your life easier: file = "test" tmp = file + "~" File.open(tmp, "w") do |out| out.puts "This line should appear at the top of each file" File.foreach file do |line| out.puts line end end File.delete file File.rename tmp, file Kind regards robert