tawheed
tawheed

Reputation: 5821

Splitting string by comma in python

I have a csv file that contains

"VANS, PASSENGER TYPE",CHEVROLET,H1500 EXPRESS AWD,5.3,8,Auto(L4),4,832,9,12,10,11.5,16.2,13.2268,E,,,,,,,,,,3900,310-340,CLKUP ,2,15,30-Jun-07,DERIVED

All I am trying to do is split by comma, do only problem with my current solution is that the first entry which happens to be "VANS, PASSENGER TYPE" has a comma but I am not interested in splitting that.

Currently I am doing something like this

with open("file.txt", "r") as ins:
   foo = ins.split(",")

Upvotes: 0

Views: 68

Answers (1)

Avinash Raj
Avinash Raj

Reputation: 174696

It's better to use csv module.

import csv
with open('file') as f:
    reader = csv.reader(f)
    for line in reader:
        print(line)

Output:

['VANS, PASSENGER TYPE', 'CHEVROLET', 'H1500 EXPRESS AWD', '5.3', '8', 'Auto(L4)', '4', '832', '9', '12', '10', '11.5', '16.2', '13.2268', 'E', '', '', '', '', '', '', '', '', '', '3900', '310-340', 'CLKUP ', '2', '15', '30-Jun-07', 'DERIVED']

Upvotes: 6

Related Questions