blob: 1bd9a30a4044d07321233af2965e0ae4fb50ba18 [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
39 lines = rdata.splitlines()
Patrick Williamsc124f4f2015-09-15 14:41:29 -050040 rmdata = data.strip().splitlines()
41 for l in rmdata:
42 for c in range(0, lines.count(l)):
43 i = lines.index(l)
44 del(lines[i])
45 write_file(path, "\n".join(lines))