Exercise 8.3 - Solution

# follow.py

import csv
import time
import os

def follow(filename):
    '''
    Generator that produces a sequence of lines being written at the end of a file.
    '''
    with open(filename,'r') as f:
        f.seek(0,os.SEEK_END)
        while True:
             line = f.readline()
             if line != '':
                 yield line
             else:
                 time.sleep(0.1)    # Sleep briefly to avoid busy wait

def convert(rows, func, keylist):
    '''
    Apply type conversion to selected keys
    '''
    for r in rows:
        for key in keylist:
            r[key] = func(r[key])
        yield r

def parse_stock_data(lines):
    '''
    Take a sequence of lines and produce a sequence of dictionaries containing stock market data.
    '''
    headers = ['name', 'price', 'date', 'time', 'change', 'open', 'high', 'low', 'volume']
    rows = csv.DictReader(lines, headers)
    rows = convert(rows, float, ['price','change','open','high','low'])
    rows = convert(rows, int, ['volume'])
    return rows

# Sample code for following the real-time log
if __name__ == '__main__':
    lines = follow('Data/stocklog.csv')
    rows  = parse_stock_data(lines)
    for r in rows:
        if r['change'] < 0:
            print '%(name)10s %(price)10.2f %(change)10.2f' % r

[ Back ]