Package Bio :: Package SCOP :: Module FileIndex
[hide private]
[frames] | no frames]

Source Code for Module Bio.SCOP.FileIndex

 1  # Copyright 2001 by Gavin E. Crooks.  All rights reserved. 
 2  # This code is part of the Biopython distribution and governed by its 
 3  # license.  Please see the LICENSE file that should have been included 
 4  # as part of this package. 
 5   
 6  # This functionality may be of general use, in which case this module should 
 7  # be moved out of the SCOP package. 
 8   
 9  import warnings 
10  warnings.warn("Bio.SCOP.FileIndex was deprecated, as it does not seem to have any users. If you do use this module, please contact the Biopython developers at biopython-dev@biopython.org to avoid permanent removal of this module") 
11   
12   
13   
14 -class defaultdict(dict):
15
16 - def __init__(self, default=None):
17 dict.__init__(self) 18 self.default = default
19
20 - def __getitem__(self, key):
21 try: 22 return dict.__getitem__(self, key) 23 except KeyError: 24 return self.default
25
26 -class FileIndex(dict) :
27 """ An in memory index that allows rapid random access into a file. 28 29 The class can be used to turn a file into a read-only 30 database. 31 """
32 - def __init__(self, filename, iterator_gen, key_gen ) :
33 """ 34 Arguments: 35 36 filename -- The file to index 37 38 iterator_gen -- A function that eats a file handle, and returns 39 a file iterator. The iterator has a method next() 40 that returns the next item to be indexed from the file. 41 42 key_gen -- A function that generates an index key from the items 43 created by the iterator. 44 """ 45 dict.__init__(self) 46 47 self.filename = filename 48 self.iterator_gen = iterator_gen 49 50 f = open(self.filename) 51 try: 52 loc = 0 53 i = self.iterator_gen(f) 54 while 1 : 55 next_thing = i.next() 56 if next_thing is None : break 57 key = key_gen(next_thing) 58 if key != None : 59 self[key]=loc 60 loc = f.tell() 61 finally : 62 f.close()
63
64 - def __getitem__(self, key) :
65 """ Return an item from the indexed file. """ 66 loc = dict.__getitem__(self,key) 67 68 f = open(self.filename) 69 try: 70 f.seek(loc) 71 thing = self.iterator_gen(f).next() 72 finally: 73 f.close() 74 return thing
75