How to split a string with commas but ignore commas in Python quotes

Possible duplicate:
How to read CSV string using ??

I saw a number of related questions, but no one directly addressed what I was trying to do. I am reading lines of text from a CSV file.

All items are in quotation marks, and some have extra commas in quotation marks. I would like to split the line along the commas, but ignore the commas in quotation marks. Is there a way to do this in Python that does not require multiple regex statements.

Example:

"114111","Planes,Trains,and Automobiles","50","BOOK" 

which I would like to analyze for 4 separate value variables:

 "114111" "Planes,Trains,and Automobiles" "50" "Book" 

Is there a simple parameter in line.split() that I am missing?

+8
python csv
source share
2 answers

Do not try to invent a wheel.

If you want to read lines from a CSV file, use the Python csv module from the standard library.

Example:

 > cat test.py import csv with open('some.csv') as f: reader = csv.reader(f) for row in reader: print(row) > cat some.csv "114111","Planes,Trains,and Automobiles","50","BOOK" > python test.py ['114111', 'Planes,Trains,and Automobiles', '50', 'BOOK'] [] 

The task is completed!

+30
source share

Perhaps you can divide by ",", that is, "[quote] [comma] [quote]"

another option comes up with an escape character, so if someone wants to insert a comma in the line they do \ c, and if they want a backslash, they do \\. Then you need to split the line and then cancel it before processing.

-5
source share

All Articles