Posted By

ronakpatel2006 on 08/11/11


Tagged

read csv


Versions (?)

Read a csv file


 / Published in: Python
 

  1. import os
  2. import sys
  3. import csv
  4.  
  5. def opencsv(filename):
  6. tfile = open(filename, "r")
  7. line = tfile.readline()
  8. tfile.close()
  9. if line[0] == '"':
  10. quote_char = '"'
  11. quote_opt = csv.QUOTE_ALL
  12. elif line[0] == "'":
  13. quote_char = "'"
  14. quote_opt = csv.QUOTE_ALL
  15. else:
  16. quote_char = '"'
  17. quote_opt = csv.QUOTE_MINIMAL
  18. if line.find('\t') != -1:
  19. delim_char = '\t'
  20. else:
  21. delim_char = ','
  22. tfile = open(filename, "rb")
  23. reader = csv.reader(tfile, delimiter=delim_char, quotechar=quote_char, quoting=quote_opt)
  24. return (tfile, reader)
  25.  
  26. def display():
  27.  
  28. ifile = open('/home/rpatel/complete_error_codes.csv', "rb")
  29. find_code = raw_input("Enter the code: ")
  30. reader = csv.reader(ifile)
  31.  
  32. rownum = 0
  33. for row in reader:
  34. if rownum == 0:
  35. header = row
  36. else:
  37. column = 0
  38. if row[1] == str(find_code):
  39. for col in row:
  40. print'%-8s: %s' % (header[column], col)
  41. column += 1
  42. break
  43. rownum += 1
  44. ifile.close()
  45.  
  46. if __name__ == '__main__':
  47.  
  48. try:
  49. display()
  50. except Exception, e:
  51. print("Exception in display: %s" % e)

Report this snippet  

You need to login to post a comment.