disk.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import os
  2. from .__init__ import Reader,Writer
  3. import json
  4. class DiskReader(Reader) :
  5. """
  6. This class is designed to read data from disk (location on hard drive)
  7. @pre : isready() == True
  8. """
  9. def __init__(self,**params):
  10. """
  11. @param path absolute path of the file to be read
  12. """
  13. Reader.__init__(self)
  14. self.path = params['path'] ;
  15. self.delimiter = params['delimiter'] if 'delimiter' in params else None
  16. def isready(self):
  17. return os.path.exists(self.path)
  18. def read(self,size=-1):
  19. """
  20. This function reads the rows from a designated location on disk
  21. @param size number of rows to be read, -1 suggests all rows
  22. """
  23. f = open(self.path,'rU')
  24. i = 1
  25. for row in f:
  26. i += 1
  27. if size == i:
  28. break
  29. if self.delimiter :
  30. yield row.split(self.char)
  31. yield row
  32. f.close()
  33. class DiskWriter(Writer):
  34. """
  35. This function writes output to disk in a designated location. The function will write a text to a text file
  36. - If a delimiter is provided it will use that to generate a xchar-delimited file
  37. - If not then the object will be dumped as is
  38. """
  39. def __init__(self,**params):
  40. Writer.__init__(self)
  41. self.cache['meta'] = {'cols':0,'rows':0,'delimiter':None}
  42. if 'path' in params:
  43. self.path = params['path']
  44. else:
  45. self.path = 'data-transport.log'
  46. self.delimiter = params['delimiter'] if 'delimiter' in params else None
  47. # if 'name' in params:
  48. # self.name = params['name'];
  49. # else:
  50. # self.name = 'data-transport.log'
  51. # if os.path.exists(self.path) == False:
  52. # os.mkdir(self.path)
  53. def meta(self):
  54. return self.cache['meta']
  55. def isready(self):
  56. """
  57. This function determines if the class is ready for execution or not
  58. i.e it determines if the preconditions of met prior execution
  59. """
  60. return True
  61. # p = self.path is not None and os.path.exists(self.path)
  62. # q = self.name is not None
  63. # return p and q
  64. def format (self,row):
  65. self.cache['meta']['cols'] += len(row) if isinstance(row,list) else len(row.keys())
  66. self.cache['meta']['rows'] += 1
  67. return (self.delimiter.join(row) if self.delimiter else json.dumps(row))+"\n"
  68. def write(self,info):
  69. """
  70. This function writes a record to a designated file
  71. @param label <passed|broken|fixed|stats>
  72. @param row row to be written
  73. """
  74. f = open(self.path,'a')
  75. f.write(self.format(info))
  76. f.close()