Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- __AUTHOR__ = 'Beegie_B'
- __DATE__ = '2014-02-21'
- import httplib, datetime, json
- BF4STAT_URL = 'api.bf4stats.com'
- LOCATION = '/api/onlinePlayers?output=json'
- OUTFILE = 'bf4data.csv'
- TIMEFORMAT = '%Y-%m-%d %H:%M'
- KEYS = ['PC', 'PS3', 'PS4', 'X360', 'XONE']
- def get_url_data(url, page):
- conn = httplib.HTTPConnection(url)
- conn.request("GET", page)
- response = conn.getresponse()
- return response.read()
- def extract_player_counts(jstr):
- data = json.loads(jstr)
- counts = {}
- counts['PC'] = str(data['pc']['count'])
- counts['PS3'] = str(data['ps3']['count'])
- counts['X360'] = str(data['xbox']['count'])
- counts['XONE'] = str(data['xone']['count'])
- counts['PS4'] = str(data['ps4']['count'])
- return counts
- def write_dict_to_csv(filename, d, keys=None, timestamp=False):
- if keys is None:
- keys = dict.keys()
- if timestamp:
- keys = ['date'] + keys
- d['date'] = datetime.datetime.now().strftime(TIMEFORMAT)
- include_header = False
- try:
- f = open(filename)
- f.close()
- except IOError:
- include_header = True
- finally:
- f = open(filename, 'a')
- if include_header:
- f.write(', '.join(keys) + '\n')
- f.write(', '.join([d[key] for key in keys]) + '\n')
- f.close()
- if __name__=='__main__':
- data = get_url_data(BF4STAT_URL, LOCATION)
- player_counts = extract_player_counts(data)
- write_dict_to_csv(OUTFILE, player_counts, KEYS, timestamp=True)
Advertisement
Add Comment
Please, Sign In to add comment