[Tutor] compare and arrange file
Emile van Sebille
emile at fenx.com
Wed Jul 13 04:32:42 CEST 2011
On 7/12/2011 4:01 PM Edgar Almonte said...
> On Tue, Jul 12, 2011 at 5:44 AM, Peter Otten<__peter__ at 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
More information about the Tutor
mailing list