Rahul99
Rahul99

Reputation: 85

How to separate comma separated data from csv file?

I have opened a csv file and I want to sort each string which is comma separated and are in same line:

ex:: file :

name,sal,dept
tom,10000,it

o/p :: each string in string variable

I have a file which is already open, so I can not use "open" API, I have to use "csv.reader" which have to read one line at a time.

Upvotes: 0

Views: 622

Answers (2)

Alex Martelli
Alex Martelli

Reputation: 881675

If the file open for reading is bound to a variable name, say fin; and assuming you're using Python 2.6, and you know the file's not empty (has at least the row with headers):

 import csv

 rd = csv.reader(fin)
 headers = next(rd)
 for data in rd:
   ...process data and headers...

In Python 2.5, use headers = rd.next() instead of headers = next(rd).

These versions use a list of fields data, which is a completely general solution (i.e., you don't need to know in advance how many columns the file has: you'll access them as data[0], data[1], etc, and the current row has len(data) fields at each leg of the loop).

If you know the file has exactly three columns and prefer to use separate names for a variable per column, change the loop header to:

 for name, sales, department in rd:

The field data as returned by the reader (just like the headers) are all strings. If you know for example that the second column is an int and want to treat it as such, start the loop with

 for data in rd:
     data[1] = int(data[1])

or, if you're using the named-variables variant:

 for name, sales, department in rd:
     sales = int(sales)

Upvotes: 2

Manrico Corazzi
Manrico Corazzi

Reputation: 11371

I don't know if I have properly understood your question. You may want to have a look at the split function described in the Python documentation anyway.

Upvotes: 0

Related Questions