By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,222 Members | 2,416 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,222 IT Pros & Developers. It's quick & easy.

Open and closing files

P: n/a
Is it defined behaviour that all files get implicitly closed when not
assigning them?

Like:

def writeFile(fName, foo):
open(fName, 'w').write(process(foo))

compared to:
def writeFile(fName, foo):
fileobj = open(fName, 'w')
fileobj.write(process(foo))
fileobj.close()

Which one is the 'official' recommended way?

Thomas
Dec 1 '06 #1
Share this Question
Share on Google+
2 Replies


P: n/a

Thomas Ploch wrote:
Is it defined behaviour that all files get implicitly closed when not
assigning them?

Like:

def writeFile(fName, foo):
open(fName, 'w').write(process(foo))

compared to:
def writeFile(fName, foo):
fileobj = open(fName, 'w')
fileobj.write(process(foo))
fileobj.close()

Which one is the 'official' recommended way?
No such thing as an 'official' way.

Nothing happens until the file object is garbage-collected. GC is
generally not under your control.

Common sense suggests that
(a) when you are reading multiple files, you close each one explicitly
(b) when you are writing a file, you close it explicitly as soon as you
are done with it. That way you can trap any error condition and do
something moderately sensible -- better than getting an error condition
during GC when your Python process is shutting down.

HTH,
John

Dec 1 '06 #2

P: n/a

John Machin wrote:
Thomas Ploch wrote:
Is it defined behaviour that all files get implicitly closed when not
assigning them?

Like:

def writeFile(fName, foo):
open(fName, 'w').write(process(foo))

compared to:
def writeFile(fName, foo):
fileobj = open(fName, 'w')
fileobj.write(process(foo))
fileobj.close()

Which one is the 'official' recommended way?

No such thing as an 'official' way.

Nothing happens until the file object is garbage-collected. GC is
generally not under your control.

Common sense suggests that
(a) when you are reading multiple files, you close each one explicitly
(b) when you are writing a file, you close it explicitly as soon as you
are done with it. That way you can trap any error condition and do
something moderately sensible -- better than getting an error condition
during GC when your Python process is shutting down.

HTH,
John
Not to mention you can get bitten on the ass by a few characters
sitting in a buffer someplace when you expect your file to have been
fully written.

Close the thing.

Cheers,
-T

Dec 1 '06 #3

This discussion thread is closed

Replies have been disabled for this discussion.