Python基础-模块
模块
模块有三种
1.标准模块,不需要单独安装,python自带模块
2.第三方模块,别人写好,使用得安装
3.自己写的python文件
import random print(random.randint(10000,99999)) #随机取一个整数 print(random.uniform(1,900)) #取一个小数 stus = ['xiaojun','hailong','yangfan','tanailing','yangyue','cc'] print(random.choice('abcdefg')) #随机取一个元素 print(random.sample(stus,2)) #随机取N个元素 l = list(range(1, 101)) print("洗牌之前", l) print(random.shuffle(l)) #洗牌,这个只能传list print("洗牌之后的", l)
作业
1、写一个函数,函数的功能是生成一批密码,存到文件里面 def gen_password(num): #num代表生成多少条密码 pass 2、密码复杂度要求 1、长度在,8-16位之间 2、密码必须包括大写字母、小写字母、数字、特殊字符 3、密码不能重复 3、生成的密码保存到文件里面 2、写一个函数,函数的功能生成一批双色球号码 def gen_seq(num): pass 1、中奖号码由6个红色球号码和1个蓝色球号码组成。 红球的范围是 1-33 篮球的范围是:1-16 2、产生的不能重复 篮球: 05 红球: 01 03 05 17 18 32 篮球: 05 红球: 01 03 05 17 18 32 篮球: 05 红球: 01 03 05 17 18 32 篮球: 05 红球: 01 03 05 17 18 32
#作业1 import random import string def gen_passwords1(): pwd_len = random.randint(8,16) upper = random.sample(string.ascii_uppercase,1) lower = random.sample(string.ascii_lowercase,1) digit = random.sample(string.digits,1) punctuation = random.sample(string.punctuation,1) other = random.sample(string.ascii_letters+string.digits+string.punctuation,pwd_len-4) res = upper+lower+digit+punctuation+other random.shuffle(res) return ''.join(res) def gen_password2(): pwd_len = random.randint(8,16) all_str = string.ascii_letters+string.digits+string.punctuation res = set(random.sample(all_str,pwd_len)) if res & set(string.ascii_uppercase) and res & set(string.digits) \ and res & set(string.ascii_lowercase) and res & set(string.punctuation): return ''.join(res) return gen_password2() all_passwords = set() num = int(input("请输入要产生多少条密码:").strip()) while len(all_passwords) != num: res = gen_passwords1()+'\n' all_passwords.add(res) with open('passwords.txt','w',encoding='utf-8') as fw: fw.writelines(all_passwords)
#列表生成式 #res = ['01','02','03','33'] #res = [] # for i in range(1,34): # res.append(str(i).zfill(2)) l = [i for i in range(10)] #先写for i in range(10),把生成的i放前面再写 print(l) res = [str(i).zfill(2) for i in range(1,34)] print(res)
#列表生成式 import random def gen_seq(): all_red_ball = [str(i).zfill(2) for i in range(1,34)] all_blue_ball = [str(i).zfill(2) for i in range(1,17)] blue = random.choice(all_blue_ball) red = random.sample(all_red_ball,6) red = ''.join(red) return '红球:%s 蓝球:%s'%(red, blue) all_seq = set() num = int(input("请输入要产生多少条密码:").strip()) while len(all_seq) != num: res = gen_seq()+'\n' all_seq.add(res) with open('seq.txt','w',encoding='utf-8') as fw: fw.writelines(all_seq)
常用模块
os模块
import os os.rename(old, new) #重命名 os.remove(f) #删除文件 os.mkdir('china/beijing') #创建文件夹,父目录存在才能创建下级目录 os.makedirs('china/beijing') #父目录不存在会自动创建 os.removedirs('china') #只能删除空文件夹 print(os.listdir("e:\\")) #显示该目录下的所有文件和文件夹 print(os.path.isdir('E:\\apache-jmeter-3.3')) #判断是否是文件夹 print(os.path.isfile('e:\\2018年度项目工作总结及规划.pptx')) #判断是否为文件 print(os.path.exists('E:\\apache-jmeter-3.3')) #判断文件或文件夹是否存在 res1 = os.system('dir') #执行操作系统命令 res2 = os.popen('ipconfig').read() #执行系统操作命令后并返回值 print(res2) os.path.join('china','a.py') #拼接路径 os.path.split(r'D:\China\beijing\a.py') #把路径和文件名分割开 os.path.dirname(r'D:\China\beijing\a.py') #取父目录 os.path.getsize(r'D:\China\beijing\a.py') #取文件大小,单位是字节 os.getcwd() #取当前目录 os.chdir(r'D:\China\beijing') #进入到哪个目录 os.path.getatime() #获取文件时间
res = os.walk('D:\\') #遍历所有目录和文件 count = 0 for cur_path,dirs,files in res: #print('文件:',files,'当前目录:',cur_path,'文件夹',dirs) for f in files: if f.endswith('py'): #count += 1 os.remove(os.path.join(cur_path,f)) print(count) def find_file(path, keyword): #查找文件的 res = os.walk(path) for cur_path, dirs, files in res: for file_name in files: if keyword in file_name: print("该文件在%s下面" %cur_path) find_file("D:\\","设备部接口新.jmx")
time模块
import time time.sleep(30) res = time.strftime('%Y-%m-%d %H:%M:%S') #取当前的格式化日期 res = time.time() #获取当前的时间戳 time_tuple = time.strptime('2038-08-29 19:23:59','%Y-%m-%d %H:%M:%S') #把格式化好的时间转成时间元组,返回的是一个时间戳 print(time.mktime(time_tuple))
#格式化时间转时间戳 def str_to_timestamp(time_str=None,format='%Y%m%d%H%M%S'): #格式化好的时间转时间戳 #不传参数的话返回当前的时间戳 if time_str: time_tuple = time.strptime(time_str, format) # 把格式化好的时间转成时间元组 timestamp = time.mktime(time_tuple) else: timestamp = time.time() return int(timestamp) print(str_to_timestamp()) print(str_to_timestamp('20391123175123')) print(str_to_timestamp('2013-08-09','%Y-%m-%d'))
res = time.gmtime(time.time())#是把时间戳转时间元组的,标准时区 res = time.localtime(time.time())#是把时间戳转时间元组的,当前时区 res2 = time.strftime('%Y-%m-%d %H:%M:%S',res) print(res2)
def timestamp_to_strtime(timestamp=None,format='%Y-%m-%d %H:%M:%S'): #这个函数是用来把时间戳转成格式化好的时间 #如果不传时间戳的话,那么就返回当前的时间 if timestamp: time_tuple = time.localtime(timestamp) str_time = time.strftime(format,time_tuple) else: str_time = time.strftime(format) return
#用当前的时间戳+相应年的秒数,时间戳转成格式化好的时间 five = str_to_timestamp() - (3*24*60*60) res = timestamp_to_strtime(five) print('3天后的时间是',res)
加密模块
import hashlib # import md5 #这个是python2里面的 password='123123' print(password.encode())#转成二进制类型的才可以加密 m = hashlib.md5(password.encode()) m = hashlib.sha1(password.encode()) m = hashlib.sha224(password.encode()) m = hashlib.sha256(password.encode()) print(m.hexdigest()) #md5加密之后是不可逆 def my_md5(s:str,salt=None): #salt是盐值 s = str(s) if salt: s = s+salt m = hashlib.md5(s.encode()) return m.hexdigest()
读Excel
import xlrd book = xlrd.open_workbook('stu.xls') sheet = book.sheet_by_index(0) sheet = book.sheet_by_name('sheet1') print(sheet.nrows) #excel里面有多少行 print(sheet.ncols) #excel里面有多少列 print(sheet.cell(0,0).value) #获取到指定单元格的内容 print(sheet.cell(0,1).value) #获取到指定单元格的内容 print(sheet.row_values(0))#获取到整行的内容 print(sheet.col_values(0))#获取到整行的内容 for i in range(sheet.nrows):#循环获取每行的内容 print(sheet.row_values(i))
写Excel
import xlwt import xlrd import xlutils #写Excel book = xlwt.Workbook() sheet = book.add_sheet('sheet1') # sheet.write(0,0,'id')#指定行和列写入内容 # sheet.write(0,1,'username') # sheet.write(0,2,'password') # # sheet.write(1,0,'1') # sheet.write(1,1,'niuhanyang') # sheet.write(1,2,'123456') # stus = [ [1,'njf','1234'], [2,'xiaojun','1234'], [3,'hailong','1234'], [4,'xiaohei','1234'], [4,'xiaohei','1234'], [4,'xiaohei','1234'], [4,'xiaohei','1234'], [4,'xiaohei','1234'], [4,'xiaohei','1234'], ] line = 0 #控制的是行 for stu in stus:#行 col = 0 for s in stu: sheet.write(line,col,s) col+=1 line+=1 book.save('stu.xls')# .xlsx
修改Excel
import xlrd from xlutils import copy book = xlrd.open_workbook('stu.xls') #先用xlrd打开一个Excel new_book = copy.copy(book) #然后用xlutils里面的copy功能,复制一个Excel sheet = new_book.get_sheet(0)#获取sheet页 sheet.write(0,1,'hello') sheet.write(1,1,'world') new_book.save('stu.xls')
操作Mysql
host='118.24.3.40' user='jxz' password='123456' #密码只能是字符串 db='jxz' port=3306#端口号只能写int类型 charset='utf8'#只能写utf8,不能写utf-8 import pymysql conn = pymysql.connect(host=host,password=password, user=user,db=db,port=port, charset=charset,autocommit=True )#建立连接 cur= conn.cursor() #建立游标 # cur.execute()#只是帮你执行sql语句 # print(cur.fetchall())#获取数据库里面的所有的结果 # print('fetchone',cur.fetchone()) #如果只有一行数据使用fetchone # sql='insert into app_myuser (username,passwd,is_admin) VALUE ("python123456","123456",1);' sql='select * from app_myuser limit 5;' cur.execute(sql) print(cur.description)#获取这个表里面的所有字段信息 # conn.commit()#提交 cur.close() conn.close() def my_db(ip,user,password,db,sql,port=3306,charset='utf8'): conn = pymysql.connect( host=ip,user=user,password=password, db=db, port=port,charset=charset,autocommit=True ) cur = conn.cursor() cur.execute(sql) res = cur.fetchall() cur.close() conn.close() return res def my_db2(sql): conn = pymysql.connect( host='118.24.3.40',user='jxz',password='123456', db='jxz', port=3306,charset='utf8',autocommit=True ) pass
汉字转拼音
import xpinyin s = xpinyin.Pinyin() py = s.get_pinyin("你好",'') print(py)
相关推荐
Lzs 2020-10-23
聚合室 2020-11-16
零 2020-09-18
Justhavefun 2020-10-22
jacktangj 2020-10-14
ChaITSimpleLove 2020-10-06
Andrea0 2020-09-18
周游列国之仕子 2020-09-15
afanti 2020-09-16
88234852 2020-09-15
YClimb 2020-09-15
风雨断肠人 2020-09-04
卖口粥湛蓝的天空 2020-09-15
stulen 2020-09-15
pythonxuexi 2020-09-06
abfdada 2020-08-26
梦的天空 2020-08-25