| Store | Cart

Suggest more finesse, please. I/O and sequences.

From: Peter Hansen <pet...@engcorp.com>
Sat, 26 Mar 2005 06:46:57 -0500
Qertoip wrote:
> Peter Hansen wrote:>>-------------------------->>import sys>>>>corpus = {}>>for word in open(sys.argv[1]).read().split():>>     corpus[word] = corpus.get( word, 0 ) + 1>>>>words = reversed(sorted(data[::-1] for data in corpus.iteritems()))>>>>open(sys.argv[2], 'w').writelines('%7d : %s\n' % data for data in words)>>--------------------------> > Is the file automatically closed in both cases?

Yes.  Either as soon as the file object has no more
references to it (with CPython), or as soon as the
application terminates or the garbage collection
executes to reclaim the objects (Jython, IronPython,
and any other Pythons that don't use reference
counting).

Either way, for a small script, it's safe.

-Peter

Recent Messages in this Thread
Qertoip Mar 25, 2005 06:17 pm
Scott David Daniels Mar 25, 2005 08:51 pm
Qertoip Mar 25, 2005 10:06 pm
Scott David Daniels Mar 25, 2005 11:30 pm
Larry Bates Mar 25, 2005 10:11 pm
Qertoip Mar 26, 2005 01:24 am
Peter Hansen Mar 26, 2005 02:09 am
Qertoip Mar 26, 2005 10:15 am
Peter Hansen Mar 26, 2005 11:46 am
Messages in this thread
Previous post: Embedding Python