1*4882a593Smuzhiyun# 2*4882a593Smuzhiyun# SPDX-License-Identifier: MIT 3*4882a593Smuzhiyun# 4*4882a593Smuzhiyun 5*4882a593Smuzhiyunimport os 6*4882a593Smuzhiyunimport re 7*4882a593Smuzhiyunimport errno 8*4882a593Smuzhiyun 9*4882a593Smuzhiyundef write_file(path, data): 10*4882a593Smuzhiyun # In case data is None, return immediately 11*4882a593Smuzhiyun if data is None: 12*4882a593Smuzhiyun return 13*4882a593Smuzhiyun wdata = data.rstrip() + "\n" 14*4882a593Smuzhiyun with open(path, "w") as f: 15*4882a593Smuzhiyun f.write(wdata) 16*4882a593Smuzhiyun 17*4882a593Smuzhiyundef append_file(path, data): 18*4882a593Smuzhiyun # In case data is None, return immediately 19*4882a593Smuzhiyun if data is None: 20*4882a593Smuzhiyun return 21*4882a593Smuzhiyun wdata = data.rstrip() + "\n" 22*4882a593Smuzhiyun with open(path, "a") as f: 23*4882a593Smuzhiyun f.write(wdata) 24*4882a593Smuzhiyun 25*4882a593Smuzhiyundef read_file(path): 26*4882a593Smuzhiyun data = None 27*4882a593Smuzhiyun with open(path) as f: 28*4882a593Smuzhiyun data = f.read() 29*4882a593Smuzhiyun return data 30*4882a593Smuzhiyun 31*4882a593Smuzhiyundef remove_from_file(path, data): 32*4882a593Smuzhiyun # In case data is None, return immediately 33*4882a593Smuzhiyun if data is None: 34*4882a593Smuzhiyun return 35*4882a593Smuzhiyun try: 36*4882a593Smuzhiyun rdata = read_file(path) 37*4882a593Smuzhiyun except IOError as e: 38*4882a593Smuzhiyun # if file does not exit, just quit, otherwise raise an exception 39*4882a593Smuzhiyun if e.errno == errno.ENOENT: 40*4882a593Smuzhiyun return 41*4882a593Smuzhiyun else: 42*4882a593Smuzhiyun raise 43*4882a593Smuzhiyun 44*4882a593Smuzhiyun contents = rdata.strip().splitlines() 45*4882a593Smuzhiyun for r in data.strip().splitlines(): 46*4882a593Smuzhiyun try: 47*4882a593Smuzhiyun contents.remove(r) 48*4882a593Smuzhiyun except ValueError: 49*4882a593Smuzhiyun pass 50*4882a593Smuzhiyun write_file(path, "\n".join(contents)) 51