[Tutor] Need help appending data to a logfile

Lukáš Němec lu.nemec at gmail.com
Mon Jun 17 20:20:50 CEST 2013


Dne 17. 6. 2013 20:17, Dave Angel napsal(a):
> On 06/17/2013 01:36 PM, Matt D wrote:
>> Hey,
>> I wrote some simple code to write data to a logfile and it works pretty
>> well (thanks guys).  Now my problem is that every time i run the program
>> the old logfile.txt is overwritten.  I need to be able to stop and start
>> the program without overwriting, or losing, the old data.  here is the
>> relavent code:
>>
>>   #  central part of the program
>>   #  lays out the GUI panel
>>   #  omitted lots for our purposes here
>>   Class panel(wx.Panel):
>>
>>          #  open a file named "logfile.txt" in "w" writing mode.
>>          #  this will create the file if it doesn't exist.
>>          self.logfile = open('logfile.txt', 'w')
>>
>>   # Updates the TextCtrl field values
>>   # and logs TextCtrl field values
>>   def update(self, field_values):
>>
>>          #logger code---------------
>>          #first write the CURRENT date/time
>>     self.logfile.write('%s,'%(str(strftime("%Y-%m-%d %H:%M:%S",
>> gmtime()))))
>>     # loop through each of the TextCtrl objects
>>     for k,v in self.fields.items():
>>              #get the value of the current TextCtrl field
>>              f = field_values.get(k, None)
>>         if f:
>>                  #output the value with trailing comma
>>                     self.logfile.write('%s,'%(str(f)))
>>         self.logfile.write('\n')
>>     #end logger code ----------------
>>
>> In addition to not deleting the old data, it would be awesome to have
>> some sort of wxPython widget that would give the user the ability to
>> 'save as', or name and save the file, from the GUI panel.
>> Thanks!
>>
>
> Clearly you didn't absorb or act on much of the advice from the last 
> time.  So this time I'll just give you a brief hint.
>
> Don't use write mode when opening the file.  Find the docs on open(), 
> and see what other choices there are.
>
>
>
Or even better, use python moto, dont re-invent the wheel, so use built 
in library logging, read the docs for it, or if you want, I can send you 
some examples how to work it, it takes some time to figure out properly...


More information about the Tutor mailing list