import random import pandas as pd used = [] class NotAccess(Exception): pass # 学号随机 def getID(): ID = [] while len(ID) < 60: new_id = random.randint(0, 100) + 201800 if new_id not in ID: ID.append(new_id) return ID # 随机取学号 def getRandomID() -> int: while True: random_id = random.randint(0, 60) + 201800 if random_id not in used: used.append(random_id) return random_id # 成绩随机 def getScore() -> dict: scores = {} # 已随机人数 tmp_num = 0 # 零分 for i in range(2): scores[getRandomID()] = 0 tmp_num += 1 # 60-70分 for i in range(random.randint(3, 6)): scores[getRandomID()] = random.randint(60, 69) + (random.randint(0, 1) * 0.5) tmp_num += 1 # 70-80分 for i in range(random.randint(6, 10)): scores[getRandomID()] = random.randint(70, 79) + (random.randint(0, 1) * 0.5) tmp_num += 1 # 80-90分 for i in range(random.randint(25, 35)): scores[getRandomID()] = random.randint(80, 89) + (random.randint(0, 1) * 0.5) tmp_num += 1 # 90-100分 for i in range(60 - tmp_num): scores[getRandomID()] = random.randint(90, 99) + (random.randint(0, 1) * 0.5) tmp_num += 1 return scores def sortScore(scores) -> list: return sorted(scores.items(), key=lambda x: x[0]) def export(scores): fd = pd.DataFrame.from_dict(scores, orient='index') fd.to_csv('成绩.csv') print("csv已导出 成绩.csv") fd.to_excel('excel已导出 成绩.xlsx') try: with open('成绩.txt', 'w', encoding='utf-8') as f: if not f: raise NotAccess("不可达") f.write(fd.to_string()) except FileNotFoundError: print("File cannot be access") except NotAccess as e: print(e) finally: print("已做出所有可能的导出") if __name__ == '__main__': ID = getID() scores = getScore() # 释放内存 del used export(scores)