问题描述: 做为 Apple Store App 独立开发者,你要搞限时促销,为你的应用生成激活码(或者优惠券),使用 Python 如何生成 200 个激活码(或者优惠券)?
需求分析:
代码编写:
#! /usr/bin/env python3
# Filename : generator.py
import os,sys
import string,random
#产生随机码的域
field = string.ascii_letters + string.digits
class generator(object):
#激活码存储位置
file_name = ''
#激活码
data = []
#追加的激活码
data_append = []
#本次激活码需要数量
need_num = 0
#本次激活码生成数量
cur_num = 0
#激活码长度需求
length = 0
def __init__(self, length =16,need_num=100):
self.length = length
self.need_num = need_num
self.file_name = os.getcwd() + os.sep + "generator.txt"
#加载已经存在的激活码
self.load()
def load(self):
try:
with open(self.file_name,"r") as file:
for line in file.readlines():
self.data.append(line)
except FileNotFoundError:
if __name__ == "__main__":
print("文件未找到,不需要加载")
except:
if __name__ == "__main__":
print("加载失败{%s},重新生成=>"%sys.exc_info()[0])
def generate(self):
while self.cur_num < self.need_num:
#生成一个随机码
rand = self.__get_one()
self.data_append.append(rand)
self.cur_num +=1
#追加
self.data.append(self.data_append)
with open(self.file_name,"a") as file:
file.write("\n")
file.writelines("\n".join(self.data_append))
def generate_one(self):
#生成一个随机码
rand = self.__get_one()
self.data.append(rand)
with open(self.file_name,"a") as file:
file.write("\n")
file.write(rand)
def __get_one(self):
rand = ''.join(random.sample(field,self.length))
while(rand in self.data):
rand = random.sample(field,self.length)
if __name__ == "__main__":
print("[激活码]=>%s"%(str(rand)))
return rand
if __name__ == "__main__":
generator = generator()
#生成一定数量的激活码。默认100个
generator.generate()
#生成一个激活码
generator.generate_one()