[Tutor] Writing to text files

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Mon Aug 22 20:15:44 CEST 2005

> It's actually fairly simply and straight forward...  Here's how to do
> it:  (I haven't officially tested this code for bugs, but I believe it
> is correct.)
> file = open("datafile.txt", "r")
> filedata = file.read()
> file.close()
> newLine = "Your new line of data with the time stamp goes here.\n" +
> filedata
> file = open("datafile.txt", "w")
> file.write(newLine)
> file.close()

Hi Byron,

The approach here is fine, but it's slightly fragile, because if anything
exceptional happens in-between writing the lines back to the file, we can
lose the data in the file.  It might be safe to first backup the original
file by renaming it to something else.

More information about the Tutor mailing list