1

I am trying to create a list from a csv file. However, I'm having a tough time using the split method because some of the attributes in the csv file has comma's that are within parenthesis. for example:

csv file:

500,403,34,"hello there, this attribute has a comma in it",567

So for example, when I iterate through the file:

for line in f:
    fields = line.split(",")

fields = ['500','403','34','"hello there','this attribute has a comma in it"','567']

How can I get it to look like this:

fields = ['500','403','34','"hello there, this attribute has a comma in it"','567']

I would like to use Regex for this, but if there is an easier way I'd love to hear it. Thanks!

3 Answers 3

2
import re
x='500,403,34,"hello there, this attribute has a comma in it",567'
print re.split(r""",(?=(?:[^"]*"[^"]*"[^"]*)*[^"]*$)""",x)

Output : ['500', '403', '34', '"hello there, this attribute has a comma in it"', '567']

Sign up to request clarification or add additional context in comments.

Comments

1

Just use the existing CSV package. Example:

import csv
with open('file.csv', 'rb') as csvfile:
    reader = csv.reader(csvfile)
        for row in reader:
            print ', '.join(row)

Comments

0

The CSV module is the easiest way to go:

import csv

with open('input.csv') as f:
    for row in csv.reader(f):
        print row

For input input.csv:

500,403,34,"hello there, this attribute has a comma in it",567
500,403,34,"hello there this attribute has no comma in it",567
500,403,34,"hello there, this attribute has multiple commas, in, it",567

The output is:

['500', '403', '34', 'hello there, this attribute has a comma in it', '567']
['500', '403', '34', 'hello there this attribute has no comma in it', '567']
['500', '403', '34', 'hello there, this attribute has multiple commas, in, it', '567']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.