def read(path, type=None, quiet=False): """ Read muti-types of files Input: path, type=["csv", "txt", "dat", "json", "pck"] Output: data """ if type == None or type not in ["csv", "txt", "dat", "json", "pck"]: if not quiet: print "Use default format: dat" type = "dat" if isExist(path): if type == "json": with open(path, mode="r") as fp: data = fp.read() data = data.replace("\n", "") data = json.loads(data) if type == "txt" or type == "dat" or type == "csv": with open(path, mode="r") as fp: data = fp.readlines() if type == "pck": with open(path, mode="r") as fp: data = pickle.load(fp) if not quiet: filesize = conv.convertBytes(os.path.getsize(path)) print "Read successfully: %s(%s)!" % (path, filesize) return data else: out_str = "ERROR: %s not exist!" % (path) return None
def save(data, path, type=None, quiet=False): """ Save muti-types of files Input: path, type=["csv", "txt", "dat", "json", "pck"] Output: data """ if type == None or type not in ["csv", "txt", "dat", "json", "pck"]: print "Use default format: dat" type = "dat" if type == "csv" or type == "dat" or type == "txt": with open(path, mode="w") as fp: fp.write(str(data)) fp.flush() if type == "json": with open(path, mode="w") as fp: json.dump(data, fp, indent=3, encoding="utf-8", ensure_ascii=False) if type == "pck": with open(path, mode="w") as fp: pickle.dump(data, fp) if not quiet: filesize = conv.convertBytes(os.path.getsize(path)) print "Save successfully: %s(%s)!" % (path, filesize)