Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import numpy as np
- class BlockedFile(object):
- """
- Fake file object that stops reading when encountering a comment.
- Reading is resumed by next_block()
- """
- def __init__(self, filename):
- self.f = open(filename, 'r')
- self.line = None
- def readline(self):
- if self.line is None:
- line = self.f.readline()
- else:
- line = self.line
- self.line = None
- if line.startswith('%'):
- # stop at comment
- return ''
- return line
- def next_block(self):
- while True:
- line = self.f.readline()
- if line.lstrip().startswith('%'):
- # skip comments
- continue
- else:
- # push to buffer
- self.line = line
- break
- def __iter__(self):
- return self
- def next(self):
- line = self.readline()
- if not line:
- raise StopIteration()
- return line
- def close(self):
- self.f.close()
- def test():
- # sample file
- f = open('test.dat', 'w')
- f.write("""\
- 1 1
- 2 2
- 3 3
- % foo
- 4 5 6
- 5 6 7
- 8 9 0
- % bar
- 7
- 8
- 9
- """)
- f.close()
- # Read the file
- f = BlockedFile('test.dat')
- data_1 = np.loadtxt(f)
- f.next_block()
- data_2 = np.loadtxt(f)
- f.next_block()
- data_3 = np.loadtxt(f)
- print data_1
- print data_2
- print data_3
- if __name__ == '__main__':
- test()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement