How to open Text File and then insert line in first position?

Hi,

I need to add a header to files, but I didn’t find how open files in
append
mode (‘a’) but positioned in first position.
Does anyone know how to do that?

Thanks

Pablo Q. wrote:

Hi,

I need to add a header to files, but I didn’t find how open files in
append
mode (‘a’) but positioned in first position.
Does anyone know how to do that?

Thanks

I would write the headers to a new file and then the content.
Then move the file over to the old file.

Easier to do it in shell (linux/mac/unix)
echo $header > tmpfile
cat oldfile >> tmpfile
mv tmpfile oldfile

If you need to do it in ruby see http://www.ruby-forum.com/topic/163631
for related discussion. Last post (at this time) by Erik has the sort
of code you need - just need to modify it a little.

There is this ‘r+’ mode which allows you to write to other parts of the
file besides appending but I don’t think it’s going to help. Someone
might want to pick me up on that.

Regards,
Daniel

Thanks to both,

This is what I was looking for.

On Aug 26, 8:11 am, “Pablo Q.” [email protected] wrote:


Pablo Q.

Try this:

file_to_read = ‘/path/to/file.txt’
header = “Text to put at top of file\n\n”
file = IO.read(file_to_read)
open(file_to_read, ‘w’) { |f| f << header << file}

Cheers,

Craig

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs