How to sort records in file

L

Lad

What is the best( easiest)way how to sort a file?
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.
Any idea?
Thanks for help
Lad
 
G

Grant Edwards

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,
 
P

Peter Otten

Grant said:
$ man sort

;)


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
 
P

Paul Rubin

What is the best( easiest)way how to sort a file?
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.

If you're using Linux, the simplest way is with the "sort" command:

sort infile -o outfile

This will sort files of basically unlimited size, as long as you have
enough disk space. The files don't have to fit in memory.

Since you're posting on c.l.py, maybe you're really asking how to read
the file in sorted order in a Python program:

import os
sorted = os.popen("sort infile")

runs the sort command in an external process.

Finally, there's a built-in sorting operation on lists:

def compare(a, b):
def key(line):
return line.split()[0]
return cmp(key(a), key(b))
lines = open("infile").readlines()
lines.sort(compare)

but that requires reading the whole file into memory, etc.
 

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

Forum statistics

Threads
474,202
Messages
2,571,057
Members
47,667
Latest member
DaniloB294

Latest Threads

Top