python练手小程序


1.生成200个指定长度的随机码


import random
import string

def rand_str(num,len=7):
    f = open('file.txt','w')
    count = 1
    for i in range(num):
        restr = ''
        chars = string.ascii_lowercase+ string.digits
        for i in range(len):
            restr += random.choice(chars)

        f.write( str(count)+ ' ' + restr +'\n')
        count += 1

    f.close()


if __name__ == '__main__':

    rand_str(200,20)


知识点:

1.随机取值:

 random.choice

2.w是写入,wb就是写入二进制文件了。

f = open('file.txt','w')

3.int转为str

str(count)


二、把1中生成的随机码存到数据库中

#-*- coding:utf-8 -*-

'''
02
'''

import string
import random
import pymysql


#用于生成随机字符串List的函数

def geneRandStr(num,len=7):

    strList = []

    for i in range(num):
        restr = ''
        chars = string.ascii_lowercase + string.digits
        for i in range(len):
            restr += random.choice(chars)
        strList.append(restr)
    return strList

#把字符串List存入数据库
def storeInMysql(codeList):

    try:
        conn = pymysql.connect(host='127.0.0.1',user = 'root',
                           password = '123456',db = 'pytest')
        cur = conn.cursor()
    except BaseException as e:
        print(e)
    else:
        try:
            cur.execute('DROP DATABASE pytest ')
            cur.execute('CREATE DATABASE IF NOT EXISTS pytest ')
            cur.execute('USE pytest')
            cur.execute('''CREATE TABLE IF NOT EXISTS code(
              id INT NOT NULL AUTO_INCREMENT,
              code VARCHAR (32) NOT NULL,
              PRIMARY KEY (id)
              )''')

            for code in codeList:
                cur.execute('INSERT INTO code(code) VALUES (%s)',(code))
                cur.connection.commit()

        except BaseException as e:
            print(e)

    finally:
        cur.close()
        conn.close()


if __name__ == '__main__':
    storeInMysql(geneRandStr(20,10))








猜你喜欢

转载自blog.csdn.net/muyimo/article/details/71176005