# Collection of code snippets by Arne Vajhøj 
# (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
RECSIZ = 4
FNM = 'pyx.fix'

def recno(ix):
   return (ix - 1) * RECSIZ

def test_write_one(f, ix, buf):
    f.seek(recno(ix))
    f.write(buf)

def test_write():
    f = open(FNM, 'r+b')
    test_write_one(f, 3, 'CCCC')
    test_write_one(f, 2, 'BBBB')
    test_write_one(f, 1, 'AAAA')
    f.close()

def test_read_sequential():
    f = open(FNM, 'rb')
    while True:
        buf = f.read(RECSIZ)
        if buf == '':
            break
        print('|%s| %d' % (buf, len(buf)))
    f.close()

def test_read_random_one(f, ix):
    f.seek(recno(ix))
    buf = f.read(RECSIZ)
    print('|%s| %d' % (buf, len(buf)))

def test_read_random():
    f = open(FNM, 'rb')
    test_read_random_one(f, 3)
    test_read_random_one(f, 2)
    test_read_random_one(f, 1)
    f.close()

print('Python seek')
test_write()
test_read_sequential()
test_read_random()
