On Tue, Jul 12, 2011 at 10:32 PM, Emile van Sebille <em...@fenx.com> wrote: > On 7/12/2011 4:01 PM Edgar Almonte said... >> >> On Tue, Jul 12, 2011 at 5:44 AM, Peter Otten<__pete...@web.de> wrote: > > <snip> >>> >>> import csv > > imports the comma separated values (csv) file handler utilities module > >>> >>> def sortkey(row): >>> if float(row[1]): >>> return row[1], True >>> else: >>> return row[2], False > > ... sortkey defines a function that accepts a cvs.reader data row, and > returns either row[1] and True or row[2] and False based on which of row[1] > and row[2] has a non-zero value > >>> >>> with open("infile.txt", "rb") as instream: >>> rows = sorted(csv.reader(instream, delimiter="|"), key=sortkey) > > rows becomes the sortkey sorted result of the lines of infile.txt > >>> >>> with open("outfile.txt", "wb") as outstream: >>> csv.writer(outstream, delimiter="|").writerows(rows) > > ... and this writes those results to outfile.txt > > you might also try the shortened: > > from csv import reader,writer > > def sortkey(row): return max(row[1],row[2]),row[1]>row[2] > > writer(open("outfile.txt", "wb"), delimiter="|").writerows( > sorted(reader(open("infile.txt", "rb"), delimiter="|"),key=sortkey)) > > > Emile > > _______________________________________________ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor >
fist time i saw the statement "with" , is part of the module csv ? , that make a loop through the file ? is not the sortkey function waiting for a paramenter ( the row ) ? i don't see how is get pass , the "key" is a parameter of sorted function ? , reader is a function of csv module ? if "with..." is a loop that go through the file is the second with inside of that loop ? ( i dont see how the write of the output file catch the line readed Thanks again for the helping of my understand _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor