By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,908 Members | 2,055 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,908 IT Pros & Developers. It's quick & easy.

Multiple delimiters with csv DictReader

P: 2
I have a csv file that is mainly comma seperated, but one of the fields has currency values in the form "$1,378.59". By just specifying a delimiter:',' in my dialect, the above value gets parsed as 1.00 and 378.59. I would also like to include ' " ' as an additional delimiter so that the string inside the quotes gets read as one string. Is there a way I can do this or a workaround? Thanks!!
Sep 26 '07 #1
Share this Question
Share on Google+
3 Replies


bvdet
Expert Mod 2.5K+
P: 2,851
I have a csv file that is mainly comma seperated, but one of the fields has currency values in the form "$1,378.59". By just specifying a delimiter:',' in my dialect, the above value gets parsed as 1.00 and 378.59. I would also like to include ' " ' as an additional delimiter so that the string inside the quotes gets read as one string. Is there a way I can do this or a workaround? Thanks!!
Using the csv module:
Expand|Select|Wrap|Line Numbers
  1. import csv
  2.  
  3. f = open('csv.txt', 'rb')
  4. for item in csv.reader(f):
  5.     print item
Sample output:
['Blues', 'Elwood', '1060 W Addison', 'Chicago, Illinois 60613']

Notice the comma in the last item. Any time a field has a comma, it must be enclosed by quotes like this:

Blues,Elwood,"1060 W Addison","Chicago, Illinois 60613"
Sep 26 '07 #2

P: 2
Thanks for your response. So you are saying that the csv reader should automatically take care of the thousand-seperator if the value is enclosed in quotes. Heres what I am using:

class dialect(csv.excel):
delimiter = '\t'

py_dict = csv.DictReader(fileHandle,dialect=dialect)

And it somehow fails to recognize the quotes as a delimiter. Is it because I am overriding it with '\t'?
Sep 26 '07 #3

bvdet
Expert Mod 2.5K+
P: 2,851
Thanks for your response. So you are saying that the csv reader should automatically take care of the thousand-seperator if the value is enclosed in quotes. Heres what I am using:

class dialect(csv.excel):
delimiter = '\t'

py_dict = csv.DictReader(fileHandle,dialect=dialect)

And it somehow fails to recognize the quotes as a delimiter. Is it because I am overriding it with '\t'?
Try this:
Expand|Select|Wrap|Line Numbers
  1. f = open('csvtab.txt', 'rb')
  2. for item in csv.reader(f, delimiter='\t'):
  3.     print item
Data:
Blues Elwood 1060 W Addison "Chicago, Illinois 60613" B263-1655-2187 116 56

Output:
['Blues', 'Elwood', '1060 W Addison', 'Chicago, Illinois 60613', 'B263-1655-2187', '116', '56']
Sep 26 '07 #4

Post your reply

Sign in to post your reply or Sign up for a free account.