Kjell Evenson
Kjell Evenson

Reputation: 31

subtract two columns in a tab'ed file (python)

I have been tinkering with some coordinates which I want to check against eachother.

I have a tab'ed filed, which consist of 6 columns. These are the last 4 columns I want to subtract, and get the result in two columns after the last coordinate column. Also tab'ed.

I want to do this for quite large files, is this possible? And if not, how can I do it with rather small files? I have done some reading, and the csv module pops up everywhere.

    337905.44   5269907.69  337905.38   5269907.78
    337917.95   5269907.55  337917.93   5269907.62
    337930.46   5269907.34  337930.48   5269907.46
    337942.97   5269907.13  337942.84   5269907.06

This is how far I got, when I gave up;


    import csv
    with open('coor.txt', newline='') as f:
        reader = csv.reader(f, delimiter=':', quoting=csv.QUOTE_NONE)

To sum up, all I want to do is to have the first and third column subtracted, and the second and fourth column subtracted, and get the difference in two columns after the last coordinate column.

Thanks in advance!

Upvotes: 0

Views: 2431

Answers (1)

Fredrik Pihl
Fredrik Pihl

Reputation: 45662

Something like this?

#!/usr/bin/env python

with open('input') as fd:
    for line in fd:
        columns=line.split()
        columns=map(float,columns)
        print "%s | \t %s \t %s" % (line.strip(), columns[0] - columns[2],
                                    columns[1] - columns[3])

Outputs

337905.44   5269907.69  337905.38   5269907.78 |     0.0599999999977     -0.089999999851
337917.95   5269907.55  337917.93   5269907.62 |     0.0200000000186     -0.070000000298
337930.46   5269907.34  337930.48   5269907.46 |     -0.0199999999604    -0.120000000112
337942.97   5269907.13  337942.84   5269907.06 |     0.129999999946      0.070000000298

Using csv-module:

import csv

with open('input', 'rb') as fd:
    reader=csv.reader(fd,delimiter='\t')
    for row in reader:
        #your calculations
        print row

Upvotes: 3

Related Questions