blob: a7233d4ca6e9150e60abd1f38c5eeb8ea1482f26 [file] [log] [blame]
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001import os
2import re
Patrick Williamsf1e5d692016-03-30 15:21:19 -05003import errno
Patrick Williamsc124f4f2015-09-15 14:41:29 -05004
5def write_file(path, data):
Patrick Williamsf1e5d692016-03-30 15:21:19 -05006 # In case data is None, return immediately
7 if data is None:
8 return
Patrick Williamsc124f4f2015-09-15 14:41:29 -05009 wdata = data.rstrip() + "\n"
10 with open(path, "w") as f:
11 f.write(wdata)
12
13def append_file(path, data):
Patrick Williamsf1e5d692016-03-30 15:21:19 -050014 # In case data is None, return immediately
15 if data is None:
16 return
Patrick Williamsc124f4f2015-09-15 14:41:29 -050017 wdata = data.rstrip() + "\n"
18 with open(path, "a") as f:
19 f.write(wdata)
20
21def read_file(path):
22 data = None
23 with open(path) as f:
24 data = f.read()
25 return data
26
27def remove_from_file(path, data):
Patrick Williamsf1e5d692016-03-30 15:21:19 -050028 # In case data is None, return immediately
29 if data is None:
30 return
31 try:
32 rdata = read_file(path)
33 except IOError as e:
34 # if file does not exit, just quit, otherwise raise an exception
35 if e.errno == errno.ENOENT:
36 return
37 else:
38 raise
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050039
40 contents = rdata.strip().splitlines()
41 for r in data.strip().splitlines():
42 try:
43 contents.remove(r)
44 except ValueError:
45 pass
46 write_file(path, "\n".join(contents))