Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 1 | import os |
| 2 | import re |
Patrick Williams | f1e5d69 | 2016-03-30 15:21:19 -0500 | [diff] [blame^] | 3 | import errno |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 4 | |
| 5 | def write_file(path, data): |
Patrick Williams | f1e5d69 | 2016-03-30 15:21:19 -0500 | [diff] [blame^] | 6 | # In case data is None, return immediately |
| 7 | if data is None: |
| 8 | return |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 9 | wdata = data.rstrip() + "\n" |
| 10 | with open(path, "w") as f: |
| 11 | f.write(wdata) |
| 12 | |
| 13 | def append_file(path, data): |
Patrick Williams | f1e5d69 | 2016-03-30 15:21:19 -0500 | [diff] [blame^] | 14 | # In case data is None, return immediately |
| 15 | if data is None: |
| 16 | return |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 17 | wdata = data.rstrip() + "\n" |
| 18 | with open(path, "a") as f: |
| 19 | f.write(wdata) |
| 20 | |
| 21 | def read_file(path): |
| 22 | data = None |
| 23 | with open(path) as f: |
| 24 | data = f.read() |
| 25 | return data |
| 26 | |
| 27 | def remove_from_file(path, data): |
Patrick Williams | f1e5d69 | 2016-03-30 15:21:19 -0500 | [diff] [blame^] | 28 | # 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 Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 40 | 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)) |