From: Dave Angel on 13 Apr 2010 22:09
> I've been told, that following code snippet is not good.
> open("myfile","w").write(astring) , because I'm neither explicitely
> closing nor using the new 'with' syntax.
> What exactly is the impact of not closing the file explicitely
> (implicitley with a 'with' block)?
> Even with my example
> I'd expected to get an exception raised if not all data could have
> been written.
> I'd also expected, that all write data is flushed as soon as the
> filehandle is out of scope (meaning in the next line of my source
> Thanks for explaining me exactly what kind of evil I could encounter
> with not explicitely closing.
Evil? No. Just undefined behavior.
The language does NOT guarantee that a close or even a flush will occur
when an object "goes out of scope." This is the same in Python as it is
in Java. There's also no exception for data not being flushed.
In one particular implementation of Python, called CPython, there are
some things that tend to help. So if you're sure you're always going to
be using this particular implementation, and understand what the
restrictions are, then go ahead and be sloppy. Similarly, on some OS
systems, files are flushed when a process ends. So if you know your
application is only going to run on those environments, you might not
bother closing files at the end of execution.
It all depends on how restrictive your execution environment is going to be.
From: Ryan Kelly on 13 Apr 2010 23:10
On Tue, 2010-04-13 at 18:19 -0700, Chris Rebert wrote:
> On Tue, Apr 13, 2010 at 5:45 PM, Giampaolo Rodola' <gnewsg(a)gmail.com> wrote:
> > What about open('foo', 'w').close().
> > Does it have the same problems?
> Well, no, but that's only because it's a pointless no-op that doesn't
> really do anything besides possibly throwing an exception (e.g. if the
> script didn't have write access to the current directory).
Actually, it will create the file if it doesn't exist, and truncate it
to zero length if it does.
http://www.rfk.id.au | This message is digitally signed. Please visit
ryan(a)rfk.id.au | http://www.rfk.id.au/ramblings/gpg/ for details
First | Prev |
Pages: 1 2
Prev: mailbox multipart
Next: Does Abstract class , interfaces there in python ?