[Tutor] Writing to text files

Alan G alan.gauld at freenet.co.uk
Mon Aug 22 12:48:38 CEST 2005

> I want to write to a text file with a timestamp, but I want to 
> newest
> entry at the top. So I want to insert the next entry to the file at 
> the
> beginning.

You will need to create a new file. Basically you need to:

Read the current  file into a list or string.
Rename the old file (foo.bak seems a common type!)
Prepend your new data
Write the new string out to a new file with the old name

You may prefer to read the existing file in line by line and write
it back out again to save memory usage.

You can see some examples of this type of file copying in my
tutorial where I print out a restaurant menu with a daily updated

Alan G
Author of the Learn to Program web tutor

More information about the Tutor mailing list