54 lines
1.5 KiB
Python
54 lines
1.5 KiB
Python
# Development
|
|
from pprint import pprint
|
|
import csv
|
|
import sys
|
|
|
|
class StripStats:
|
|
|
|
def __init__(self, url, output_file='out.csv', fields=None):
|
|
self.output_file = output_file
|
|
self.rows = self.strip_data(url)
|
|
if fields:
|
|
self.fields = fields
|
|
else:
|
|
self.fields = self.rows[0].keys
|
|
|
|
#
|
|
# Instance methods
|
|
#
|
|
|
|
# Actions
|
|
def write_data(self):
|
|
if not self.rows:
|
|
raise ValueError, "'self.rows' is empty"
|
|
|
|
is_empty = False
|
|
if self.is_output_file_empty():
|
|
is_empty = True
|
|
open(self.output_file, 'w').close() #truncate whitespace
|
|
|
|
with open(self.output_file, 'ab') as file_handle:
|
|
writer = csv.DictWriter(
|
|
file_handle, self.fields, extrasaction='raise', dialect='excel')
|
|
if is_empty:
|
|
writer.writeheader()
|
|
for row in self.rows:
|
|
writer.writerow(row)
|
|
|
|
# Utility
|
|
def is_output_file_empty(self):
|
|
try:
|
|
with open(self.output_file, 'r') as file_handle:
|
|
for line in file_handle:
|
|
if line.strip():
|
|
return False
|
|
except:
|
|
pass
|
|
return True
|
|
|
|
# Abstract methods
|
|
def strip_data(self, url):
|
|
"""Override this abstract method in derived class to. Returns an array of dictionaries
|
|
where each dictionary's keys correspond to a particular matchup's data."""
|
|
pass
|