[Tutor] Writing to text files

Bob Gailer bgailer at alum.rpi.edu
Mon Aug 22 19:10:06 CEST 2005


At 08:09 AM 8/22/2005, Byron wrote:
>Hi Johan,
>
>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")

This is an example of rebinding to a name originally bound to a builtin 
function.
In other words, file is a builtin function; assigning to file makes the 
builtin inaccessible.
So it is a good idea to avoid such assignments.

>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()

or if you like terseness:
newText = newLine + open("datafile.txt", "r").read()
open("datafile.txt", "w").write(newText )

Bob Gailer
303 442 2625 home
720 938 2625 cell 



More information about the Tutor mailing list