1. 程式人生 > >PYTHON自動化Day6-函式多個返回值和匿名函式、列表生成式,三元運算子,os模組,sys模組,時間模組,字典排序,資料庫操作,加密(md5)

PYTHON自動化Day6-函式多個返回值和匿名函式、列表生成式,三元運算子,os模組,sys模組,時間模組,字典排序,資料庫操作,加密(md5)

一.函式多個返回值和匿名函式

#函式返回多個值,用一個變數接收
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'))