github.com/platonnetwork/platon-go@v0.7.6/cases/common/load_file.py (about) 1 import json 2 import os 3 import hashlib 4 import yaml 5 6 7 class LoadFile(object): 8 """ 9 Convert json or yaml files to python dictionary or list dictionary 10 """ 11 12 def __init__(self, file): 13 if file.split('.')[-1] != 'yaml' and file.split('.')[-1] != 'json' and file.split('.')[-1] != 'yml': 14 raise Exception("the file format must be yaml or json") 15 self.file = file 16 17 def get_data(self): 18 """ 19 call this method to get the result 20 """ 21 if self.file.split('.')[-1] == "json": 22 return self.load_json() 23 return self.load_yaml() 24 25 def load_json(self): 26 """ 27 Convert json file to dictionary 28 """ 29 try: 30 with open(self.file, encoding="utf-8") as f: 31 result = json.load(f) 32 if isinstance(result, list): 33 result = [i for i in result if i != ''] 34 return result 35 except FileNotFoundError as e: 36 raise e 37 38 def load_yaml(self): 39 """ 40 Convert yaml file to dictionary 41 """ 42 try: 43 with open(self.file, encoding="utf-8")as f: 44 result = yaml.load(f) 45 if isinstance(result, list): 46 result = [i for i in result if i != ''] 47 return result 48 except FileNotFoundError as e: 49 raise e 50 51 52 def get_all_file(path): 53 """ 54 Get all yaml or json files 55 :param path: 56 :return: 57 """ 58 try: 59 result = [os.path.abspath(os.path.join(path, filename)) for filename in os.listdir( 60 path) if filename.endswith(".json") or filename.endswith(".yml") or filename.endswith(".yaml")] 61 return result 62 except FileNotFoundError as e: 63 raise e 64 65 66 def get_file(path): 67 """ 68 Get all yaml or json files 69 :param path: 70 :return: 71 """ 72 try: 73 result = [] 74 for x, _, _ in os.walk(path): 75 if os.listdir(x): 76 result += get_all_file(x) 77 else: 78 result += x 79 return result 80 except FileNotFoundError as e: 81 raise e 82 83 84 def get_f(collsion_list): 85 """ 86 get the maximum number of cheat nodes 87 :param collsion_list: 88 :return: 89 """ 90 num = len(collsion_list) 91 if num < 3: 92 raise Exception("the number of consensus nodes is less than 3") 93 if num == 3: 94 return 0 95 f = (num - 1) / 3 96 return int(f) 97 98 99 def get_f_for_n(n): 100 """ 101 Get the maximum number of cheat nodes based on the total number of consensus nodes 102 :param n: 103 :return: 104 """ 105 num = n 106 if num < 3: 107 raise Exception("the number of consensus nodes is less than 3") 108 if num == 3: 109 return 0 110 f = (num - 1) / 3 111 return int(f) 112 113 114 def get_file_time(file) -> int: 115 if not os.path.exists(file): 116 raise Exception("file is not exists") 117 return int(os.path.getctime(file)) 118 119 120 def calc_hash(file): 121 with open(file, 'rb') as f: 122 sha1obj = hashlib.sha1() 123 sha1obj.update(f.read()) 124 result_hash = sha1obj.hexdigest() 125 return result_hash 126 127 128 if __name__ == "__main__": 129 calc_hash(r"D:\python\PlatON-Tests\deploy\bin\platon")