frazman
frazman

Reputation: 33243

Reading from csv file Python

I am trying to solve this problem. I am reading data from csv fiile which has the following columns:

id, name, price

So i use the following code to read the csv:

import sys
import csv as input

def readFile(path):
    try:
        finput = input.reader(open(path,'rb'),delimiter=',',quotechar='|')
    except IOError as (errno,strerror):
            print "I/O error({0}): {1}".format(errno,strerror)
    except:
            print "Unexpected Error: ",sys.exc_info()[0]
            raise
    # covert format into list
    fmod = list(finput)
    return fmod

but the problem is the name field can be like

name, item_det now that " , " creates a trouble for me.. instead of reading the name field as a single entity having a comma in the description.. it splits that particular field. How do I solve this. Thanks

Upvotes: 1

Views: 3326

Answers (2)

Scott A
Scott A

Reputation: 7834

CSV is exactly that: "Comma Separated". You either need to quote the name field:

|name,item_det|

Or use an escape character, but you have to turn it on by setting quoting to QUOTE_NONE:

reader = csv.reader(open(path, "rb"), delimiter=',', quoting=csv.QUOTE_NONE, escapechar="\\")

Example:

name\,item_det

Otherwise, don't use the csv module.

Upvotes: 1

ktdrv
ktdrv

Reputation: 3673

Just make sure that any single values that contain your delimiter char (,) are enclosed in the quotechar (|, in your example). Thus, any time the name field in a row is of the form <name>, <item_det> the row should read something like ... ,|<name>, <item_det>|, ....

Upvotes: 1

Related Questions