View Full Version : Inserting text into a file

01 January 2004, 09:53 PM
Hi. I'm having some problems understanding the Mel docs about the "r", "w", "a" modes when opening a file.

What I want to do is print some stuff to a file (clearing it first to overwrite any old file - that would be the "w" mode I suppose), then I want to go back to a specified line in the file and insert some text (or overwrite) at that line.

I've tried storing the "chunks" of text as strings first and then printing them to the file in the order I want them, but this method (although it works) slows my script down about 10 times.

Does anyone have any idea how to do this?

01 January 2004, 05:13 PM
OK, I solved it by writing to a tempfile and then closing and reopening the tempfile in "r" mode and then copying from the tempfile to the "real file" in the correct order and then deleting the tempfile.

The tempfile solution solved some other problems too, like getting half-finished files if the user aborts the script execution.

I'm still curious about some nice methods for first writing to a file and then going back and inserting text - there must be more efficient ways than creating a tempfile.

CGTalk Moderation
01 January 2006, 05:00 AM
This thread has been automatically closed as it remained inactive for 12 months. If you wish to continue the discussion, please create a new thread in the appropriate forum.