CSV import with Python; incorrect "," delimiter behavior
Question: I am using the csv module in the following manner

    
    
    header = '"Id","IsDeleted","MasterRecordId","Salutation","FirstName","LastName","Name","Type","RecordTypeId","ParentId","BillingStreet","BillingCity","BillingState","BillingPostalCode","BillingCountry","BillingLatitude"'
    header_c = csv.reader(header, delimiter=',', quotechar='"')
    
    names = []
    for row in header_c:
      names.append(row)
    

Inspecting names returns:

    
    
    [['Id'], ['', ''], ['IsDeleted'], ['', ''], ['MasterRecordId'], ['', ''], ['Salutation'], ['', ''], ['FirstName'], ['', ''], ['LastName'], ['', ''], ['Name'], ['', ''], ['Type'], ['', ''], ['RecordTypeId'], ['', ''], ['ParentId'], ['', ''], ['BillingStreet'], ['', ''], ['BillingCity'], ['', ''], ['BillingState'], ['', ''], ['BillingPostalCode'], ['', ''], ['BillingCountry'], ['', ''], ['BillingLatitude']]
    

I could ignore all the odd entries, keeping 0, 2, 4, ...., but I don't
understand what I am doing wrong and why the commas are being kept as entries.
What do I have to change in order for the comma's to be dropped. 'IsDeleted'
should be the second entry (names[1])

Thanks in advance.


Answer: You should pass a file-like object (or any other iterable) to
[csv.reader](http://docs.python.org/2/library/csv.html#csv.reader) as a first
parameter.

> csv.reader(csvfile, dialect='excel', **fmtparams)
>
> Return a reader object which will iterate over lines in the given csvfile.
> csvfile can be any object which supports the iterator protocol and returns a
> string each time its next() method is called — file objects and list objects
> are both suitable.

One option is to read the string into the `StringIO` buffer:

    
    
    from StringIO import StringIO
    header_c = csv.reader(StringIO(header), delimiter=',', quotechar='"')
    

Then, in names, you'll get:

    
    
    [['Id', 'IsDeleted', 'MasterRecordId', 'Salutation', 'FirstName', 'LastName', 'Name', 'Type', 'RecordTypeId', 'ParentId', 'BillingStreet', 'BillingCity', 'BillingState', 'BillingPostalCode', 'BillingCountry', 'BillingLatitude']]
    

