Advertisement
Guest User

Untitled

a guest
May 28th, 2017
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.49 KB | None | 0 0
  1. import numpy as np
  2.  
  3. class BlockedFile(object):
  4. """
  5. Fake file object that stops reading when encountering a comment.
  6. Reading is resumed by next_block()
  7. """
  8.  
  9. def __init__(self, filename):
  10. self.f = open(filename, 'r')
  11. self.line = None
  12.  
  13. def readline(self):
  14. if self.line is None:
  15. line = self.f.readline()
  16. else:
  17. line = self.line
  18. self.line = None
  19. if line.startswith('%'):
  20. # stop at comment
  21. return ''
  22. return line
  23.  
  24. def next_block(self):
  25. while True:
  26. line = self.f.readline()
  27. if line.lstrip().startswith('%'):
  28. # skip comments
  29. continue
  30. else:
  31. # push to buffer
  32. self.line = line
  33. break
  34.  
  35. def __iter__(self):
  36. return self
  37.  
  38. def next(self):
  39. line = self.readline()
  40. if not line:
  41. raise StopIteration()
  42. return line
  43.  
  44. def close(self):
  45. self.f.close()
  46.  
  47. def test():
  48. # sample file
  49. f = open('test.dat', 'w')
  50. f.write("""\
  51. 1 1
  52. 2 2
  53. 3 3
  54. % foo
  55. 4 5 6
  56. 5 6 7
  57. 8 9 0
  58. % bar
  59. 7
  60. 8
  61. 9
  62. """)
  63. f.close()
  64.  
  65. # Read the file
  66. f = BlockedFile('test.dat')
  67.  
  68. data_1 = np.loadtxt(f)
  69. f.next_block()
  70. data_2 = np.loadtxt(f)
  71. f.next_block()
  72. data_3 = np.loadtxt(f)
  73.  
  74. print data_1
  75. print data_2
  76. print data_3
  77.  
  78. if __name__ == '__main__':
  79. test()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement