[Tutor] Need help appending data to a logfile

Alan Gauld alan.gauld at btinternet.com
Sun Jun 30 02:51:55 CEST 2013


On 29/06/13 16:00, Matt D wrote:
>>>       with tempfile.NamedTemporaryFile('a+t',) as tf:
>>>           self.logfile = tf

This could give problems.

with guarantees to close the file at the end of the block.
But you have assigned it to self.logfile.
So when the file is closed (and tempfile then deletes the
file on disk) your self.logfile points at... nothing?!

If you are going to assign to self.logfile I'd probably
recommend not using 'with' since in this case you want
the file to hang around after the 'with' block ends.

>>> or what i have now:
>>>
>>>       self.f = tempfile.NamedTemporaryFile()

But this is totally different since it needs an explicit close.

>>> 'f' is the file the user opens but it has to be named up by the main
>>> class constructor or the program gives this error:
>>>
>>> ValueError: I/O operation on closed file

I have no idea what that means.
You don;t pass in a name from the user?
I'm not sure what you mean by the "main class constructor"
And I can't really know what the error is saying without
a full stacktrace.

> So i should tell it NOT to delete itself?  i was under the impression
> that having it delete itself upon program close is a good thing.

It usually is but I understood it was on FILE close not PROGRAM close. 
Very different things...

> thought the point of not using variables for this sort of thing is to
> save memory space.

variables in Python are just names so take up very little memory. But 
the objects in memory that they refer to can be very big.  But a file 
object is not big even when the file on disk is huge. So storing the log 
data in a file is sensible but you still want variables to point
to the file object. And that object needs to be open for you to write to it.

> the value error is from trying to write to a file that is not open.
> apparently the file dialog is not opening the file in way that i can use
> like that.

Or maybe its getting closed again immediately?

> having the file dialog be able to return the file name that
> the user opens and having that file available to the loop that writes
> the data would be ideal.

That is the usual way of doing it. Just store the filename and use it to 
open the logfile as needed for writing.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list