[Tutor] Need help appending data to a logfile

Matt D md123 at nycap.rr.com
Fri Jun 28 21:54:48 CEST 2013


On 06/28/2013 09:42 AM, Steven D'Aprano wrote:
> On 28/06/13 23:18, Matt D wrote:
> 
>> what if i did some thing like this i saw on stackoverflow:
>>
>> f = open("bigfile.txt", "w")
> 
> That clears any existing content of bigfile.txt, and opens it for
> writing. Do you intend to clear the content?
> 
> 
>> for tempfile in tempfiles:
> 
> What is in tempfiles? A list of files opened for reading? Where does
> this list come from?
> 
> 
>>      while True:
>>          data = tempfile.read(65536)
>>          if data:
>>              f.write(data)
>>          else:
>>              break
> 
> This copies the content of each tempfile into bigfile.txt.
> 
> 
>> could i make the 'logfile.txt. a tempfile?
> 
> I don't know. What do you mean by tempfile?
> 
> 
>> and could the f.write be changed to f.append?
> 
> No, files do not have an append method. Open the file in append mode,
> then all writes will append to the end of the file.
> 
> 
So what i tried was this:

import tempfile

 #self.logfile = open('logfile.txt', 'a')
 self.logfile = tempfile.NamedTemporaryFile()

obviously i commented out the old way i opened the log file. my idea is
that the new temporary self.logfile will behave exactly as the old
self.logfile.  then to get the temporary self.logfile into the file the
user chooses i decided to try this:

#open file dialog -----------------------------
def openFile(self, evt):
    with wx.FileDialog(self, "Choose a file", os.getcwd(), "",
"*.txt*", wx.SAVE) as dlg:
       if dlg.ShowModal() == wx.ID_OK:
            path = dlg.GetPath()
            mypath = os.path.basename(path)
            with open(mypath, "a") as f:
                f.write(self.logfile)
                self.logfile.close()

my idea was that everytime the user clicked the button the temporary
self.logfile would be writen to to 'f' and then self.logfile would be
destroyed.  sense 'f' is opened in append; and the self.logfile is
destroyed after each push of the button, then every time the button is
pushed only new data will be appended to file the user chooses.

But its not working.  nothing gets put in the user opened file 'f'??
What am I missing or is the approach totally wrong?  Thanks!


More information about the Tutor mailing list