Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #52033

Re: Sort lines in a plain text file alphanumerically

References <520058D7.10105@Gmail.com> <CAN1F8qVU4wPHT=gMA1x6vpp0ccyxwPjiPBCLBvK3=T2S2dj9Sw@mail.gmail.com> <5200D210.9030003@Gmail.com> <CAPTjJmqMLYXNGEnEzi0u=g6uu0apz0BabOGgftAYdDN0XcQF4w@mail.gmail.com>
From Joshua Landau <joshua@landau.ws>
Date 2013-08-06 12:44 +0100
Subject Re: Sort lines in a plain text file alphanumerically
Newsgroups comp.lang.python
Message-ID <mailman.245.1375789517.1251.python-list@python.org> (permalink)

Show all headers | View raw


On 6 August 2013 11:52, Chris Angelico <rosuav@gmail.com> wrote:
> On Tue, Aug 6, 2013 at 11:38 AM, Devyn Collier Johnson
> <devyncjohnson@gmail.com> wrote:
>>     with open('/home/collier/pytest/sort.TXT') as file:
>>         sorted(file, key=str.casefold, reverse=True)
>>
>>
>> Thanks for the advice Joshua. I find these tips very useful. However, how
>> would I close the files, or would they close after the "with" construct is
>> complete?
>
>
> That's the whole point of 'with'. It calls open(),

To be pedantic, it does not. open is called by the time the with gets involved.

> then calls
> __enter__, and it guarantees to call __exit__ before executing any
> code following the with block. With a file object, __exit__ will close
> the file.


To make it more obvious for Devyn¹, with is used any time you need a
simple guarantee of when things are "closed", for any particular
meaning. One popular usage, just as a taster, is with changing
directories so that the original directory is restored upon completion
of the sub-tasks.

¹ And so it doesn't look like I wrote a whole post to be pedantic

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: Sort lines in a plain text file alphanumerically Joshua Landau <joshua@landau.ws> - 2013-08-06 12:44 +0100

csiph-web