Q:

Compare two columns' number and output result

I have two columns' number and I would like to compare them.
Then output file will be smaller one in Column 2 and larger one in Column 1.
For example, below is my XX.csv file.
c1,c2
1015,945
1028,958
1901,1966
10016,9946
133,203
5292,5362
299,369
457,527
file = open ('input.csv','rb')
fi = file.readlines()
new_collect = []
final = []

for row in fi:
    row_new = row.rstrip().split(',')    

    if row_new[1] > row_new[2]:
        new_collect =  row_new[2] + ',' + row_new[1]
        final.append(new_collect)

    elif row_new[2] > row_new[1]:
        new_collect = row_new[2] + ',' + row_new[1]
        final.append(new_collect)

fo =  open('output.csv', 'wb')
fo.write('\n'.join(final)+'\n')
fo.close()

But my result was not correct. Results were not consistent (Column 1 > Column 2).
Anyone can help? Otherwise a better way to do so?
Thanks! 

A:

The main mistake in your code is that you are not comparing numbers, but strings, so "2" is greater than "10".
I have some other remarks:

avoid using file as variable name as it's a reserved name.
you can iterate with a "for" statement over a file object to proces a line at a time
when you access text files you should avoid using binary mode
use "with" statements to ensure the files are properly closing

Here is my proposed solution:
with open('input.csv', 'r') as ifile:
    with open('output.csv', 'w') as ofile:
        for line in ifile:
            try:
                c1, c2 = [int(val.strip()) for val in line.split(',', 1)]
            except ValueError:
                # skip malformed lines
                continue
            ofile.write("%s,%s\n" % (
                (c1, c2) if c1 > c2 else (c2, c1)))

