[Tutor] Writing to text files

Byron byron at christianfreebies.com
Mon Aug 22 23:39:13 CEST 2005

Danny Yoo wrote:

>>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()
>>newLine = "Your new line of data with the time stamp goes here.\n" +
>>file = open("datafile.txt", "w")
>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.

Hi Danny,

I agree 100% with your statement.  The reason why I left it in its 
"fragile" state was to help keep the example provided simple and 
straight forward.  Since this is a "beginners" group, I wanted to 
confuse by adding extra protection to it.  ;-)


More information about the Tutor mailing list