agile
agile

Reputation: 77

read line and split line of csv file but has comma in a cell

I have a string line and tried split with the delimiter ','

tp = 'A,B,C,"6G,1A",1,2\r\n'
tp.split(',')

and get the results as with the length of 7

['A', 'B', 'C', '"6G', '1A"', '1', '2\r\n']

but I want to get the result as to get the length 6

['A', 'B', 'C', '"6G,1A"', '1', '2\r\n']

how can I do that?

Upvotes: 1

Views: 90

Answers (2)

Job Evers
Job Evers

Reputation: 4557

https://docs.python.org/3/library/csv.html#csv.reader

>>> import csv
>>> tp = 'A,B,C,"6G,1A",1,2\r\n'
>>> rows = list(csv.reader([tp]))
>>> rows
[['A', 'B', 'C', '6G,1A', '1', '2']]

Upvotes: 2

JamesNEW
JamesNEW

Reputation: 147

You can use regex, in fact, once you know how to use regex.

It is much faster and easier for you to extract text.

tp = 'A,B,C,"6G,1A",1,2\r\n'
import re
ab = [s for s in re.split("(,|\\\".*?\\\"|'.*?')", tp)if s.strip(",")]
print(len(ab))
print(ab)

6
['A', 'B', 'C', '"6G,1A"', '1', '2\r\n']

Upvotes: -1

Related Questions