-
Notifications
You must be signed in to change notification settings - Fork 38
/
Copy pathutil.py
73 lines (64 loc) · 2.1 KB
/
util.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
try: import urllib.request as urllib2
except ImportError: import urllib2
import urllib
import os
import pickle
import logging
DATA_PATH = '.\\data\\'
# http://stackoverflow.com/questions/36932/whats-the-best-way-to-implement-an-enum-in-python
def enum(*sequential, **named):
enums = dict(zip(sequential, range(len(sequential))), **named)
reverse = dict((value, key) for key, value in enums.items())
enums['reverse_mapping'] = reverse
return type('Enum', (), enums)
def flexfilter(items, key, values):
if values is None:
return items
if type(values) is not list:
values = [values]
# TODO: use zip to handle multiple k/v pairs
return filter(lambda item: getattr(item, key, None) in values, items)
def write_to_file(filename, content, path=DATA_PATH):
location = path + filename
logging.debug('Writing to file: {}'.format(location))
file = open(location, 'w')
file.write(content)
file.close()
def read_from_file(filename, path=DATA_PATH):
location = path + filename
logging.debug('Reading from file: {}'.format(location))
file = open(location, 'r')
contents = file.read()
return contents
def pickle_it(filename, content, path=DATA_PATH):
location = path + filename
logging.debug('Pickling to file: {}'.format(location))
file = open(location, 'wb')
pickle.dump(content, file)
file.close()
def pickle_load(filename, path=DATA_PATH):
location = path + filename
logging.debug('Loading pickle from file: {}'.format(location))
file = open(location, 'rb')
contents = pickle.load(file)
file.close()
return contents
def file_exists(filename, path=DATA_PATH):
location = path + filename
logging.debug('Looking up file: {}'.format(location))
try:
with open(location, 'r') as f:
logging.debug('File {} exists.'.format(location))
return True
except IOError as e:
logging.error('File {} does not exist.'.format(location))
return False
def get_page(url):
logging.debug('Loading data from {}.'.format(url))
try:
request = urllib2.urlopen(url)
response = str(request.read())
return response
except urllib2.URLError as e:
logging.error('Error accessing web page {}.'.format(url))
raise e