zoukankan      html  css  js  c++  java
  • python生成固定格式且不会重复的用户名

    代码如下:

    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

     

  • 相关阅读:
    iOS 自动识别URL(链接)功能的实现
    iOS 如何查看崩溃日志
    Swift-- 闭包
    Swift--方法(函数)
    Swift--控制流
    Swift--字典的了解
    数据存储与访问之——SharedPreferences
    汇编指令之STOS、REP
    汇编指令之ADC、SBB、XCHG、MOVS指令
    pushad与popad
  • 原文地址:https://www.cnblogs.com/xiamaojjie/p/14093127.html
Copyright © 2011-2022 走看看