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

How to parse csv using DictReader?

P: 2
Im trying to create a visualisation from radiation data from Japan, from this website: http://www.sendung.de/japan-radiation-open-data/
It is in csv format. I was told python is good for parsing csv.
Im struggling to get to grips with how to use the csv module to parse specific rows of data. I tried using DictReader but Im really not getting anywhere, total noob.

There are four column headers: station_id, datetime, sa, ra

I need to get the data for every row with a specific station_id e.g. all the data for every instance of station_id: 1070000016.

Thanks in advance for any help.
Mar 24 '11 #1
Share this Question
Share on Google+
2 Replies


bvdet
Expert Mod 2.5K+
P: 2,851
I think this will do what you are looking for:
Expand|Select|Wrap|Line Numbers
  1. import csv
  2.  
  3. labels = ['station_id', 'datetime', 'sa', 'ra']
  4. fn = r'D:\SDS2_7.0\macro\Work In Progress\station_data_1h.csv'
  5.  
  6. station = '1070000016'
  7.  
  8. f = open(fn, 'rb')
  9.  
  10. reader = csv.DictReader(f, labels, dialect='excel-tab')
  11.  
  12. station_data = [(item["sa"],
  13.                  item["ra"],
  14.                  item["datetime"]) for item in reader if \
  15.                 item['station_id'] == station]
  16.  
  17. f.close()
  18.  
  19. print "Data for station %s" % (station)
  20. print "\n".join(["%s\t%s\t%s" % (item) for item in station_data])
Output:
Expand|Select|Wrap|Line Numbers
  1. >>> Data for station 1070000016
  2. -999    -888    2011-03-24 20:10:00
  3. -999    -888    2011-03-24 20:20:00
  4. -999    -888    2011-03-24 20:30:00
  5. -999    -888    2011-03-24 20:40:00
  6. -999    -999    2011-03-24 20:50:00
  7. >>> 
Mar 24 '11 #2

P: 2
That was surprisingly straight forward - thank you very much!
Apr 5 '11 #3

Post your reply

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