sorting strings written to files

Alex Martelli aleax at aleax.it
Sat Apr 12 15:52:39 EDT 2003


<posted & mailed>

onefatman wrote:

> Can someone help me?
> 
> I have a small phone directory .dat file that has the entries
> written to it as strings with three fields in each, separated by \t
> and ended by \n.
> 
> e.g.
> phbook.write("Joe\tNobody\t62907243\n")
> phbook.write("Daniel\tStevens\t62962328\n")
> phbook.write("Ellen\tWay\t62910758\n")
> phbook.write("Jason\tGreig\t62314587\n")
> 
> it has a function that allows you to write new entries, but i need to

How does a .dat file "have a function"?  That's not clear to me...

> know how to sort them by first name, and then by last name when the
> first names are the same.

With Python, you can read your file into memory as a list of lists of
fields, sort the list, then write it out again.  The following function
for example would do it, if called with the filename of your .dat
file (e.g. the string "C:/ofm/wot.dat" if that's where's your file
lives -- remember you can use plain slashes, handier than backlashes \n,
even if you run on Windows machines):

def sortofm(filename):
    filein = open(filename)
    listoflists = [ line[:-1].split('\t') for line in filein ]
    filein.close()

    listoflists.sort()

    fileou = open(filename, 'w')
    fileou.writelines(['\t'.join(line) for line in listoflists])
    fileou.close()


In this case, the natural ("lexicographical order") sort of lists
of lists of strings does exactly what you want, because the first
name is the first field, and the last name the second field.  In
more general cases, you'd want to use the "decorate-sort-undecorate"
idiom abundantly explained in a zillion previous posts to this NG
(use Goggle Advanced Group Search for those), the "Python Cookbook",
"Python in a Nutshell", and no doubt many, many other places too;-).


> Also, does anyone know how to delete details and change details? it
> would be a big help. thanks.

Not sure what the "details" are supposed to be.  In general, once
you've read your .dat file into memory as a list of lists (as in
the first three statements of the above function sortofm) and
before you write it back (as in the last three statements thereof),
you can perform any alteration (that leaves listoflists' items in
the same general shape) using Python indexing, list methods, etc.


Alex





More information about the Python-list mailing list