代码如下:
import os import yaml import io class UserName(object): yaml.warnings({'YAMLLoadWarning': False}) def __init__(self, loop_num, prefix_name, path_=None): """ :param loop_num: 循环次数 :param prefix_name: 前缀名称,如传"Knight",就生成Knight1,Knight2... :param path_: 配置文件路径,可以不传,不传默认在工程目录下生成username.yml文件 """ self.loop_num = loop_num self.prefix_name = prefix_name self.path = None if path_ is None: self.path = os.getcwd() + '\username.yml' else: self.path = path_ def write_yml(self, num=0): data = {'num': num} with io.open(self.path, 'w', encoding="utf-8") as wf: yaml.dump(data, wf) def read_yml(self): with io.open(self.path, 'r', encoding="utf-8") as rf: yml_data = yaml.load(rf) return yml_data.get('num', 0) def add_user_name(self): """原有基础上添加用户名称""" start_value = self.read_yml() num = start_value name_list = [] for i in range(start_value, self.loop_num + start_value): print(f"{self.prefix_name}{i}") num += 1 name_list.append(f"{self.prefix_name}{i}") self.write_yml(num) return name_list def create_user_name(self): """创建用户名称""" self.write_yml() start_value = self.read_yml() num = start_value name_list = [] for i in range(start_value, self.loop_num + start_value): print(f"{self.prefix_name}{i}") num += 1 name_list.append(f"{self.prefix_name}{i}") self.write_yml(num) return name_list def run(self): if os.path.isfile(self.path): self.add_user_name() else: self.create_user_name() if __name__ == '__main__': name = UserName(6, "Knight") name.run()
运行效果如图:每次会自动加1