day6
一.函数多个返回值和匿名函数
#函数返回多个值,用一个变量接收
def say():
num1=1
num2=2
num3=3
return num1,num2,num3
res=say()
print(res) #打印出来是元组。 函数如果返回多个值的话,会把返回的值都放在一个元组里
#函数返回多个值,多个变量接收
res1,res2,res3=say()
print(res1)
print(res2)
print(res3) #分别打印三个值。函数返回多个值,分别指定变量接收可以得到每个单独的返回值
#匿名函数:这个函数功能简单,只用一次
res=lambda x:x+1
print(res(1))
二.列表生成式
import random red_num=random.sample(range(1,34),6) new_num=[str(num).zfill(2) for num in red_num]#列表生成式 # new_num=[] 上面这一行等于下面这四行 # for num in red_num: # tmp=str(num).zfill(2) # new_num.append(tmp) print(new_num) #例子:列表生成式 # l=[i for i in range(1,101,2)] #是list,生成100以内的奇数 #如果列表生成式外层变成(): l=(i for i in range(1,101,2)) #不是list,不是元组,生成一个生成器 结果:<generator object <genexpr> at 0x000002987E855830> 生成器 print(l) # for i in l: # print(i) # 循环输出l,能得到正确数字 #()生成一个生成器,节省内存,按照一定的规则得出结果,只占用一块内存空间,[]每个元素都占用一块内存空间,生成器只能通过循环取来用 print(l.__next__()) print(l.__next__()) # 不能根据下标取值,__next__()可以取到下一个值
三.三元运算符
#三元运算符 a=5 b=4 # if a > b: # c=a # else: # c=b c=a if a>b else b #三元表达式,等同于上面四行
四.os模块
import os
#对操作系统的一些操作
print(os.getcwd())#取当前工作目录
os.chmod("x.py",2)#给文件/目录加权限,对Windows的下面不好使
# 1 执行
# 2 写
# 4 读
# #chmod
print(os.chdir("../day5"))#更改当前目录
print(os.getcwd())
#
print(os.makedirs("nhy/python"))#递归创建文件夹,父目录不存在时创建父目录
print(os.mkdir("zll/huangrong"))#创建文件夹
# makedirs 创建文件夹的时候,如果父目录不存在会自动帮你创建父目录
print(os.removedirs("nhy/python"))#递归删除空目录
print(os.rmdir("test2"))#删除指定的文件夹
#只能删除空目录
os.remove("test2")#只能删除文件
os.rmdir('test2') #只能删文件夹
print(os.listdir('e:\\'))#列出一个目录下的所有文件
os.rename("test","test1")#重命名
print(os.stat("x.py"))#获取文件信息
print(os.sep)#当前操作系统的路径分隔符 #
# day5+os.sep+x.py
print(os.linesep)#当前操作系统的换行符
# \n \r\n
print(os.pathsep)#当前系统的环境变量中每个路径的分隔符,linux是:,windows是;
print(os.environ)#当前系统的环境变量
print(os.name)#当前系统名称 Windows系统都是nt linux都是posix
res = os.system('ipconfig') #执行操作系统命令的,但是获取不到结果
res = os.popen('ipconfig').read() #可以获取到命令执行的结果
# __file__ #获取到当前文件的绝对路径
print(os.path.abspath(__file__))#获取绝对路径
print(os.path.split("/usr/hehe/hehe.txt"))#分割路径和文件名
print(os.path.dirname("e:\\syz\\ly-code"))#获取父目录,获取它的上一级目录
print(os.path.basename("e:\\syz\\ly-code\\a.txt"))#获取最后一级,如果是文件显示文件名,如果是目录显示目录名
print(os.path.exists(r"E:\syz\ly-code\day6"))#目录/文件是否存在
print(os.path.isabs("../day5"))#判断是否是绝对路径
print(os.path.isfile("xiaohei.py"))
#判断是否是一个文件,1、文件要存在2、必须是一个文件
print(os.path.isdir("e:\\syz1"))#是否是一个路径,目录是否存在
size = os.path.getsize('x.py') #获取文件的大小
#不能超过2m
print(size)
print(os.path.join("root",'hehe','mysql','a.sql'))#拼接成一个路径
#获取目录下内容
os.listdir() #只能列出内容
#os.walk() 获取到文件下的内容,得到的是生成器
for abs_path,dir,file in os.walk(r'E:\syz\ly-code\day6'):
# #
print(abs_path,dir,file)
# abs_path 当前循环的绝对路径
# dir 目录下面所有的文件夹 [ ]
# file 目录下面的所有文件 []
小练习:
#把双数日期的日志,写点东西进去
#1.获取log目录下面所有文件 os.walk()
#2.根据文件名来判断,是否双数日期,分割字符串,取到日期
#3.日期%2==0
#4.打开文件open()
# import os
# for root, dirs, files in os.walk(r"logs\logs"):
# for i in files:
# a=i.split('.')[0]
# if int(a.split('-')[2])%2==0:
# # with open(root+os.sep+i,"w") as f:
# open(os.path.join(root, i),'w').write("xxxx")
#
#
# import os
# for root,dir,file in os.walk(r'logs\logs'):
# for i in file:
# if int(i.split('.')[0].split('-')[-1])%2==0:
# open(os.path.join(root,i),'w').write("lily")
import os
for abs_path,dir,file in os.walk(r'logs\logs'):
for i in file:
print(i)
if int(i.split('.')[0].split('-')[-1]) % 2 == 0:
open(os.path.join(abs_path,i),'w',encoding='utf-8').write('hang')
五.sys模块
#给python添加环境变量 import sys
print(sys.platform) #判断操作系统
print(sys.path) #python 环境变量
#当你的文件中需要引入不在当前文件夹下的文件时,需要把上层文件夹加入环境变量
sys.path.append(r'D:\besttest\自动化\Day3')#把这个路径加入path的第一位,可以提高导入效率 sys.path.insert(0,r'D:\besttest\自动化\Day3') import zl #导入时会执行zl.py一遍 from zl import my #不要写*,因为import很多文件时,就不知道是哪个文件里的方法了 my() #导入文件时,先在当前目录下找py文件,没有的话到python的环境变量path中的路径下去找 print(sys.argv) #用来获取命令行里面运行py文件的时候传入的参数
脚本接收参数的方法:
import sys
command=sys.argv
print(command)
if len(command)>1:
cmd1=command[1] #接收第一个参数,如果有第二个就是[2]
if cmd1=='--help':
print('这个是帮助文档'
'这个python文件用来说明sys.argv的作用')
elif cmd1=='os':
print(sys.platform)
六.时间模块
import time
# 1. 时间戳 从unix元年到现在,秒
# 2. 格式化好的时间
print(time.time())
#
# time.sleep(3)
print(time.strftime('%Y%m%d%H%M'))
print(time.strftime('%D %H:%M:%S'))
print(time.strftime('%y'))
#时间与时间戳互相转换
#先转换为时间元组
print(time.gmtime()) # 默认取的是标准时区
print(time.localtime()) #取当前时区的时间,参数为“秒” ,不传参数是当前时间
print(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime()))
print(time.strftime(str(time.time()).split('.')[0]))
# ***********时间戳转换为格式化时间
def timestamp_to_format(timestamp=None,format='%Y-%m-%d %H:%M:%S'):
if timestamp:
time_tuple = time.localtime(timestamp)
res = time.strftime(format,time_tuple)
else:
res = time.strftime(format)
return res
# ***********
# ************格式化时间转换为时间戳
print(time.strptime('2018-4-21','%Y-%m-%d'))
print(time.mktime(time.strptime('2018-4-21','%Y-%m-%d')))
def format_to_timestamp(str=None,format='%Y%m%d%H%M%S'):
if str:
tp = time.strptime(str,format)
res = time.mktime(tp)
else:
res = time.time()
# 没有参数就是当前时间
return int(res)
# ***********
print(format_to_timestamp())
print(format_to_timestamp('2008-08-08','%Y-%m-%d'))
print(format_to_timestamp('20080808200801'))
print(format_to_timestamp('200808082008'))
import datetime
print('当前时间: ' , datetime.datetime.today()) #精确时间
print('当前时间: ' , datetime.date.today()) #精确到‘天’
five_days_later = datetime.date.today() + datetime.timedelta(days=5)
two_days_before = datetime.date.today() + datetime.timedelta(days=-2)
ten_minutes_later = datetime.datetime.today() + datetime.timedelta(minutes=10)
print(type(five_days_later))
print('5天后的时间: ' , five_days_later)
print('2天前的时间: ' , two_days_before)
print('10分钟后的时间: ' , ten_minutes_later)
七. 字典排序
d={'a':1,'b':2,'c':3}
print(d.items()) #字典是无序的,直接对字典排序是不存在的
#结果 dict_items([('a', 1), ('b', 2), ('c', 3)])
res=sorted(d.items(),key=lambda x:x[1]) #根据字典value排序
# sorted做了两件事:1.循环 2.排序 循环的时候把每一个二维数组传给lambda,
# lambda中返回二维数组的下标为1的元素作为key,sorted再根据这个key排序
#print(res)
#sort
l=[
[1,2,3,4],
[1,2,3,4],
[1,2,3,4],
[1,2,3,4],
[1,2,3,4],
]
for d in l:
print(d)
#结果
# [1, 2, 3, 4]
# [1, 2, 3, 4]
# [1, 2, 3, 4]
# [1, 2, 3, 4]
for a,b,c,d in l:
print(a,b,c,d)
#结果
# 1 2 3 4
# 1 2 3 4
# 1 2 3 4
# 1 2 3 4
# 1 2 3 4
def is_float(s:str,l:list): #传参指定类型
s = str(s)
if s.count('.')==1:#小数点个数
s_list = s.split('.')
left = s_list[0] #小数点左边
right = s_list[1] #小数点右边
if left.isdigit() and right.isdigit(): #正小数
return True
elif left.startswith('-') and left.count('-')==1 and \
left.split('-')[1].isdigit() and \
right.isdigit(): #判断合法负小数
return True
return False
def my(name:str):
print(name)
my("xiao")
my(['234','w3er']) #虽然指定了参数类型,但是其实没有作用,知道这种参数指定类型的写法就行了,没有用
八.数据库操作
import pymysql
# 1、 连接数据库 账号、密码、ip、端口号、数据库
# 2、建立游标
# 3、执行sql
# 4、获取结果
# 5、关闭游标
# 6、连接关闭
conn = pymysql.connect(
host='118.24.3.40',user='jxz',passwd='123456',
port=3306,db='jxz',charset='utf8'
#port必须为int
#charset这里必须为utf8
)
cur = conn.cursor()
cur.execute('insert into zhangli_users values("zhangli","xxxxxxxxxxxx");')
cur.execute('commit;')
conn.commit()
cur.execute('select * from zhangli_users where username = "zhangli";')
res = cur.fetchall()
print(res)
cur.execute('select * from zhangli_users where username = "hang";')
res = cur.fetchall()
print(res)
cur.close()#关闭游标
conn.close()#关闭连接
#一个优化的db方法, 更加好的方法讲了class之后会讲
def my_db(host,user,passwd,db,sql,port=3306,charset='utf8'):
import pymysql
conn = pymysql.connect(user=user,host=host,port=port,passwd=passwd,db=db,charset=charset)
cur = conn.cursor() #建立游标
cur.execute(sql) #执行sql
if sql.strip()[:6].upper() == 'SELECT'
if sql.startwith('select'):
res = cur.fetchall()
else:
conn.commit()
res = 'OK'
cur.close()
conn.close()
return res
九. 加密(md5)
import hashlib
passwd = 'password'
m = hashlib.md5()
print(passwd.encode(),'\n')
m.update(passwd.encode()) #不能直接对string加密,必须是byte类型才能加密
print(m.hexdigest())
def my_md5(string1):
import hashlib
new_str = string1.encode()
# new_str1 = b'%s'%string1 #两者作用一样
m = hashlib.md5() #md5实例化
m1 = hashlib.sha256()
m.update(new_str)
m1.update(new_str)
return m.hexdigest(),m1.hexdigest()
print(my_md5('password'))

浙公网安备 33010602011771号