Posted By

magicrebirth on 03/22/11


Tagged

file csv comma


Versions (?)

Who likes this?

4 people have marked this snippet as a favorite

doryexmachina
jeremydouglass
jbyerson
guillermoj88gmailcom


CSV reading in python


 / Published in: Python
 

URL: http://www.doughellmann.com/PyMOTW/csv/

  1. # Use reader() to create a an object for reading data from a CSV file. The reader can be used as an iterator
  2. # to process the rows of the file in order. For example:
  3.  
  4. import csv
  5. import sys
  6.  
  7. f = open(sys.argv[1], 'rt')
  8. try:
  9. reader = csv.reader(f)
  10. for row in reader:
  11. print row
  12. finally:
  13. f.close()
  14.  
  15.  
  16. # the original file:
  17.  
  18. "Title 1","Title 2","Title 3"
  19. 1,"a",08/18/07
  20. 2,"b",08/19/07
  21. 3,"c",08/20/07
  22. 4,"d",08/21/07
  23. 5,"e",08/22/07
  24. 6,"f",08/23/07
  25. 7,"g",08/24/07
  26. 8,"h",08/25/07
  27. 9,"i",08/26/07
  28.  
  29.  
  30. # the result:
  31.  
  32. $ python csv_reader.py testdata.csv
  33.  
  34. ['Title 1', 'Title 2', 'Title 3']
  35. ['1', 'a', '08/18/07']
  36. ['2', 'b', '08/19/07']
  37. ['3', 'c', '08/20/07']
  38. ['4', 'd', '08/21/07']
  39. ['5', 'e', '08/22/07']
  40. ['6', 'f', '08/23/07']
  41. ['7', 'g', '08/24/07']
  42. ['8', 'h', '08/25/07']
  43. ['9', 'i', '08/26/07']
  44.  
  45.  
  46.  
  47.  
  48.  
  49.  
  50.  
  51. # In addition to working with sequences of data, the csv module includes classes for working # with rows as dictionaries so that the fields can be named. The DictReader and DictWriter # # classes translate rows to dictionaries instead of lists. Keys for the dictionary can be # # passed in, or inferred from the first row in the input (when the row contains headers).
  52.  
  53.  
  54.  
  55. import csv
  56. import sys
  57.  
  58. f = open(sys.argv[1], 'rt')
  59. try:
  60. reader = csv.DictReader(f)
  61. for row in reader:
  62. print row
  63. finally:
  64. f.close()
  65.  
  66.  
  67. # returns:
  68.  
  69.  
  70. $ python csv_dictreader.py testdata.csv
  71.  
  72. {'Title 1': '1', 'Title 3': '08/18/07', 'Title 2': 'a'}
  73. {'Title 1': '2', 'Title 3': '08/19/07', 'Title 2': 'b'}
  74. {'Title 1': '3', 'Title 3': '08/20/07', 'Title 2': 'c'}
  75. {'Title 1': '4', 'Title 3': '08/21/07', 'Title 2': 'd'}
  76. {'Title 1': '5', 'Title 3': '08/22/07', 'Title 2': 'e'}
  77. {'Title 1': '6', 'Title 3': '08/23/07', 'Title 2': 'f'}
  78. {'Title 1': '7', 'Title 3': '08/24/07', 'Title 2': 'g'}
  79. {'Title 1': '8', 'Title 3': '08/25/07', 'Title 2': 'h'}
  80. {'Title 1': '9', 'Title 3': '08/26/07', 'Title 2': 'i'}

Report this snippet  

You need to login to post a comment.