How to sort records in file
Fri Aug 13 23:39:56 CEST 2004
export at hope.cz (Lad) writes:
> 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:
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):
return cmp(key(a), key(b))
lines = open("infile").readlines()
but that requires reading the whole file into memory, etc.
More information about the Python-list