How to sort records in file
Peter Otten
__peter__ at web.de
Fri Aug 13 17:16:34 EDT 2004
Grant Edwards wrote:
> On 2004-08-13, Lad <export at hope.cz> wrote:
>
>> What is the best( easiest)way how to sort a file?
>
> $ man sort
>
> ;)
>
>> I have a file where each record consists of 3 fields( 3 words)
>> and I would like to sort records by the first field( word)in
>> each record.
>
> lines = file('myfilename').readlines()
> lines.sort()
> for l in lines:
> print l,
>
Or
lines = file('myfilename').readlines()
lines = [(line.split(None, 1)[0], i, line)
for (i, line) in enumerate(lines)]
lines.sort()
lines = [line for (_, _, line) in lines]
for l in lines:
print l,
if you want to keep the order stable.
Peter
More information about the Python-list
mailing list