[Tutor] Need help appending data to a logfile
Alan Gauld
alan.gauld at btinternet.com
Sat Jun 29 02:04:53 CEST 2013
On 28/06/13 22:25, Matt D wrote:
> Python UI. I have a thread that waits on new data and when it comes in
> it gets displayed in TextCtrl fields. every time this happens my logger
> puts those values into a text file one row at a time.
>
> this how i open and the file for logging data:
>
> # open a file named
> "logfile.txt" in "a" append mode;
> self.logfile = open('logfile.txt', 'a')
What I don't understand is why you are using a hard coded filename?
Why not use the user generated filename here when you first open the
file? You can either set it as part of user preferences in a config file
or prompt the user if one hasn't been set or use a default value if they
don't set it. But however it gets set it shouldn't need to
be hard coded.
> and i have a loop that writes 8 comma separated values in row with this:
>
> self.logfile.write('%s,'%(str(f))
It might be better to build the string and then write it out once to the
file. But that's a minor matter.
> however, using this setup the user cannot select the file to save the
> log to, it just gets written into the home folder. so i came up with
> this is to allow the user can open a file from the UI:
>
> #open file dialog -----------------------------
> def openFile(self, evt):
> with wx.FileDialog(self, "Choose a file", os.getcwd(), "",
> "*.*", wx.OPEN) as dlg:
> if dlg.ShowModal() == wx.ID_OK:
> path = dlg.GetPath()
> mypath = os.path.basename(path)
> #with open(mypath, "a") as f:
>
> but i hadn't figured a way to get what is in the 'logfile.txt' into the
> file the user opens with the file dialog. so i was trying this:
OK, There is nothing special about that its just copying data into a new
file. The bit I don't understand is why continue to log the data in the
hardcoded name? Why not change the name of the log file? If need be you
can copy any existing logfile(or rename it) into the user supplied name
but then all new log entries go to the new file.
Its this strange business of maintaining two files I don't understand.
> ...the tempfile is closed
> which i was under the impression would destroy the file automatically
> and free up the memory.
It destroys the file object in memory but that does nothing
to the file on disk.
After all if you closed a file in your editor you wouldn't
expect it to be deleted from your hard drive!
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
More information about the Tutor
mailing list