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

P

Pablo Q.

[Note: parts of this message were removed to make it a legal post.]

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
 
D

Daniel Bush

Pablo said:
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
 
C

Craig

[Note:  parts of this message were removed to make it a legal post.]

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

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
 
P

Pablo Q.

[Note: parts of this message were removed to make it a legal post.]

Thanks to both,

This is what I was looking for.

2008/8/26 Craig said:
[Note: parts of this message were removed to make it a legal post.]

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

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top