Open and closing files

T

Thomas Ploch

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
 
J

John Machin

Thomas said:
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
 
T

tleeuwenburg

John said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,576
Members
45,054
Latest member
LucyCarper

Latest Threads

Top