Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I split a line by commas, but ignore commas within quotes Python [duplicate]

Tags:

python

csv

Possible Duplicate:
How to read a CSV line with "?

I have seen a number of related questions but none have directly addressed what I am trying to do. I am reading in lines of text from a CSV file.

All the items are in quotes and some have additional commas within the quotes. I would like to split the line along commas, but ignore the commas within quotes. Is there a way to do this within Python that does not require a number of regex statements.

An example is:

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

which I would like parsed into 4 separate variables of values:

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

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

like image 723
chrisfs Avatar asked Oct 07 '11 02:10

chrisfs


1 Answers

Don't try to re-invent the wheel.

If you want to read lines from a CSV file, use Python's 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']
[]

Job done!

like image 135
Johnsyweb Avatar answered Nov 15 '22 15:11

Johnsyweb