Currently, I want to parse a csv file which has 4 items per line and separate by comma. For example:
1, "2,3", 4, 5
How can I split it into :
[1,"2,3",4,5]
I try to use csv.reader
, but the outcome still in wrong way. Can anyone help?
THX!
Currently, I want to parse a csv file which has 4 items per line and separate by comma. For example:
1, "2,3", 4, 5
How can I split it into :
[1,"2,3",4,5]
I try to use csv.reader
, but the outcome still in wrong way. Can anyone help?
THX!
csv.reader
will not do type conversion, but something like this perhaps:
In [1]: import csv
In [2]: data = ['1, "2,3", 4, 5']
In [3]: next(csv.reader(data, skipinitialspace=True))
Out[3]: ['1', '2,3', '4', '5']
"""
[xxx.csv]
1, "2,3", 4, 5
"""
import re
f = open("xxx.csv")
line = f.readline() # line = '1, "2,3", 4, 5'
startUnit = False # " is for start or end
token = ""
answer=[]
for i in line:
if startUnit==False and re.match("[0-9]", i):
answer.append(int(i))
elif i=='"':
if startUnit==True:
answer.append(token)
startUnit = not startUnit
elif startUnit==True:
token+=i
elif startUnit==False:
token=""
print answer
This is simple example. It can make other exceptions because the code is only for your example. (1, "2,3", 4, 5) I hope it is helpful for you