Basic class to parse variable field CSV files.


/ Published in: Python
Save to your folder(s)



Copy this code and paste it in your HTML
  1. #!/bin/env python
  2. #-------------------------------------------------------------------------------
  3. import csv
  4.  
  5. file = '/tmp/225056.txt'
  6.  
  7. class parseDynamicCsv(object):
  8. ''' This class reads take a CSV file as an argument.
  9. The CSV file is read in to a list object.
  10. The last line of the list is popd off to determine the number of field
  11. values in the CSV.
  12. several methods are created for accessing the following data:
  13. * The colum count returned as a string.
  14. * Only the header lines as determined by the col count.
  15. * Only the data lines (minus last line) of the CSV.
  16. known bug: last line of each CSV file is not added back to the list. '''
  17.  
  18. def __init__(self, file):
  19. self.book1 = csv.reader(open(file))
  20. self.csv = list()
  21. for line in self.book1:
  22. self.csv.append(line)
  23. self.csvLastline = self.csv[-1]
  24. for row in self.csvLastline:
  25. self.csvNumOfCols = len(row.split())
  26. def csvColCount(self):
  27. return '%d' % self.csvNumOfCols
  28. def csvData(self):
  29. self.csvDataOnly = self.csv[self.csvNumOfCols:]
  30. return self.csvDataOnly
  31. def csvHeading(self):
  32. self.csvHeadingOnly = self.csv[:self.csvNumOfCols]
  33. return self.csvHeadingOnly
  34. def __strp__(self):
  35. for line in self.csv:
  36. self.lines += '%s\n' % (line)
  37. return self.lines
  38. def __repr__(self):
  39. self.lines = str()
  40. for line in self.csv:
  41. self.lines += '%s\n' % (line)
  42. return self.lines

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.