[Tutor] Need help appending data to a logfile

Matt D md123 at nycap.rr.com
Mon Jul 1 03:41:31 CEST 2013


On 06/30/2013 01:43 PM, Alan Gauld wrote:
> On 30/06/13 16:42, Matt D wrote:
> 
>> im sorry i don't understand how to pass the file name from the open
>> dialog into the update method?  I'm sorry i just don't get it.   so if
>> the user opened file is 'handle' like this?:
> 
> OK, technically you probably donb;t want to pasws it into the metjod but
> to store it in an attribute of the object.
> 
>>   def openFile(self, evt):
>>          with wx.FileDialog(self, "Choose a file", os.getcwd(), "",
>> "*.txt*", wx.OPEN) as dlg:
>>             if dlg.ShowModal() == wx.ID_OK:
>>                  self.logpath = dlg.GetPath()
> 
> Now self.logpath holds a record of the full path to the log file.
> (assuming dlg.getPath does return the full path, I haven't
> used wxPython for a while...)
> 
>> def update(self, field_values):
>>      with open(self.logpath, 'a')  as logfile:
>>          # format the line and write to file as before
> 
> And that is all you need.
> logfile is now your open logfile object referencing the file named by
> the user in the dialog. Because we opened it in a 'with' construct it
> will automatically be closed at the end of the block ready to be
> reopened next time update gets called.
> 
> And that is it. No more should be required. Provided you have permission
> to write to the file/folder then you are now logging
> to the file specified by the user.
> 
I got it done with this:

def openFile(self, evt):
        with wx.FileDialog(self, "Choose a file", os.getcwd(), "",
"*.txt*", wx.OPEN) as dlg:
           if dlg.ShowModal() == wx.ID_OK:
                path = dlg.GetPath()
                in_data = self.logfile.read()
                user_file = open(path, 'a')
                user_file.write(in_data)
                user_file.close()

so when the user starts the program strait away its automatically
logging.  if  the user wishes, before closing, he can save the logged
data to any file he wishes.  if the program is left running unattended,
for lets say five days, and the program dies its ok because its
automatically sort of 'backed up' in the logfile.txt and can be appended
to the appropriate file on restart.  no variables or arrays or lists
hogging memory.




More information about the Tutor mailing list