python生成固定格式且不会重复的用户名

2021-03-11 21:33

阅读:617

标签:spl   文件路径   效果   coding   main   path   run   creat   get   

代码如下:

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 self.path is None:
            self.path = os.getcwd() + \\username.yml
        else:
            self.path = path_

    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)

    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 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(3, "Knight")
    name.run()

运行效果如图:每次会自动加1

技术图片

 

 技术图片

 

 

python生成固定格式且不会重复的用户名

标签:spl   文件路径   效果   coding   main   path   run   creat   get   

原文地址:https://www.cnblogs.com/xiamaojjie/p/14093127.html


评论


亲,登录后才可以留言!