[Tutor] Writing to text files
Orri Ganel
singingxduck at gmail.com
Mon Aug 22 19:06:13 CEST 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")
>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()
>
>---
>
>Hope this helps,
>
>Byron :-)
>---
>
>
>
>
>Johan Geldenhuys wrote:
>
>
>
>>Hi all,
>>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.
>>I can create and append to a file and then the latest entry is at the
>>bottom.
>>Any ideas how this is done please?
>>
>>Thanks,
>>
>>Johan
>>
>>------------------------------------------------------------------------
>>
>>_______________________________________________
>>Tutor maillist - Tutor at python.org
>>http://mail.python.org/mailman/listinfo/tutor
>>
>>
>>
>>
>
>
>_______________________________________________
>Tutor maillist - Tutor at python.org
>http://mail.python.org/mailman/listinfo/tutor
>
>
>
No . . . when you open a file as "w" it erases whatever was there before:
>>> f = open("ban.txt", "w")
>>> f.write("ban")
>>> f.close()
>>> f = open("ban.txt", "r")
>>> f.read()
'ban'
>>> f.close()
>>> f = open("ban.txt", "w")
>>> f.close()
>>> f = open("ban.txt", "r")
>>> f.read()
''
--
Email: singingxduck AT gmail DOT com
AIM: singingxduck
Programming Python for the fun of it.
More information about the Tutor
mailing list