tags:

views:

133

answers:

3

Good morning.

I have series of data in cvs file like below,

1,,,

1,137.1,1198,1.6

2,159,300,0.4

3,176,253,0.3

4,197,231,0.3

5,198,525,0.7

6,199,326,0.4

7,215,183,0.2

8,217.1,178,0.2

9,244.2,416,0.5

10,245.1,316,0.4

I want to extract specific data from second column for example 217.1 and 245.1 and have them concatenated into a new file like,

8,217.1,178,0.2

10,245.1,316,0.4

I use cvs module to read my cvs file, but, I can't extract specific data as I desire. Could anyone kindly please help me. Thank you.

A: 

Edit: Misunderstood what the question was about, sorry.

I'm not sure where the problem is, You mean row not column?

As you can see in the docs for csv module

You can easily access each row:

>>> import csv  
>>> spamReader = csv.reader(open('eggs.csv'), delimiter=',', quotechar='|')  
>>> for row in spamReader:  
...     print ', '.join(row)  
Spam, Spam, Spam, Spam, Spam, Baked Beans  
Spam, Lovely Spam, Wonderful Spam  

And (ok my python days are some years old) for the columns you could e.g just do

result += row[0] + "," + row[4]
InsertNickHere
+2  A: 
results = []
reader = csv.reader(open('file.csv'))
for line in reader:  # iterate over the lines in the csv
    if line[1] in ['217.1','245.1']:  # check if the 2nd element is one you're looking for
        results.append(line)    # if so, add this line the the results list

or if you want to convert to numbers, replace the last line with

        results.append([float(x) for x in line])  # append a list of floats instead of strings
Ofri Raviv
A: 

I hope this helps:

import csv
r = csv.reader(file(r'orig.csv'))
w = csv.writer(file(r'new.csv', 'w'))
for line in r:
    if line[0] in ['8','10']: # look for the data in lines 8 and 10
        w.writerow(line)
Adam