1. 程式人生 > 其它 >Python中庫的管理/OS/time/json實戰

Python中庫的管理/OS/time/json實戰

一.庫的管理

1.標準庫:安裝python直譯器後,直接自帶的

os,sys,json,csv,time,datatime,hashib

2.第三方的庫:全球頂級程式設計師編寫的(有專門的網站可以下載)

安裝方式:

1)線上安裝

pip3 install 庫的名稱

pip3 uninstall 庫的名稱

pip3 install -u 庫的名稱

2)離線安裝

3)常用的第三方庫

selenium:UI測試框架

pip3 install selenium √

Appium:移動UI測試框架

requests:介面測試框架

pip3 install requests √

pymsql:操作mySQL

pip3 install pymysql √

xlrd:操作Excel檔案

pip3 install xlrd √

Django:全棧WEB框架

flask:輕量級WEB框架

fast:非同步WEB框架

Pytest:單元測試框架

pip3 install pytest √

 

3.自定義的庫:自己編寫的python檔案

 

二.OS實戰

針對路徑的處理

1.獲取當前路徑

2.獲取目錄下的所有檔案和資料夾

3.獲取檔案和目錄資訊

import os  #匯入os
 print('獲取當前路徑:',os.getcwd())
# #獲取目錄下的所有檔案和資料夾
for item in
os.listdir(path=os.getcwd()):
print(item) print('獲取檔案和目錄資訊:',os.stat('C:/'))

 

 

 

 

4.獲取當前路徑(最常使用這種方法)

5.獲取當前路徑的上一級路徑

#獲取當前路徑
print(os.path.dirname(__file__))
#獲取路徑的上一級路徑
print(os.path.dirname(os.path.dirname(__file__)))

 

 

實戰:

需求:新建一個data資料夾,下建一個login.txt記事本,裡面輸入內容。從當前路徑讀取login.txt裡面的內容

base_dir=os.path.dirname(os.path.dirname(__file__))#獲取路徑的上一級路徑
filePath
=os.path.join(base_dir,'data','login.txt')#合併路徑 with open(filePath,'r') as f:#讀取檔案內容 print(f.read())

 

 

6.獲取作業系統:
7.獲取環境變數:
8.判斷檔案是否存在:

print('獲取作業系統',os.name)
print('環境變數:',os.environ)
print('判斷檔案是否存在:',os.path.exists(filePath))

 

 

三.time實戰

1)time模組提供了各種與時間有關的庫

1.獲取時間戳:print(time.time())

2.獲取當前時間字串格式:print(time.ctime())

import time
print('獲取時間戳:',time.time())
print('當前時間字串格式:',time.ctime())
#休眠,秒為單位
 time.sleep(3)  #3秒後輸出
 print('hello word')

3.輸出當前時間

localeTime=time.localtime(time.time())
print('年:{0},月:{1},日:{2}'.format(
   localeTime.tm_year,localeTime.tm_mon,localeTime.tm_mday
))
print('中國人方式:',time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())) #獲取時間精確到時分秒
print('中國人方式:',time.strftime('%Y-%m-%d %x',time.localtime()))       #只獲取年月日

 

 

2)相比time的模組,datetime也是表示時間的,但是會更加直觀

1.獲取當前時間:print(datetime.datetime.now()

 

 2.在前面時間基礎上增加N天或N小時:print(datetime.datetime.now()+datetime.timedelta(days=n))

3.時間戳轉換格式:print(datetime.datetime.fromtimestamp(time.time()))

print('當前時間:',datetime.datetime.now())
#在前面時間基礎上增加N天或N小時
print(datetime.datetime.now()+datetime.timedelta(days=10))
#時間戳轉換格式
print(datetime.datetime.fromtimestamp(time.time()))

 

 

open API 開放平臺

加密方式:

1.對請求引數(字典)進行排序

2.key=value&key=value

3.進行md5的加密,生成金鑰

hashlib實戰

import hashlib
#做網路爬蟲的urllib
from urllib import parse
import time
def sign():
    dict1={"name":"lm","age":20,"work":"testDev",'time':time.time()}
    #對請求引數進行ascill碼排序
    data=dict(sorted(dict1.items(),key=lambda item:item[0]))
#把請求引數處理成Key=value&key1=value1&key2=value2
    data=parse.urlencode(data)
#進行md5的加密
    m=hashlib.md5()
#要把字串的資料處理成bytes資料型別
    m.update(data.encode('utf-8'))
    return m.hexdigest()
print(sign())

 

 

 

四.JSON實戰

序列化:把記憶體⾥的資料型別轉為字串的資料型別,使能夠儲存到硬碟或通過⽹絡傳輸到遠端,因為硬碟或者⽹絡傳輸時只接受bytes的資料型別。簡單的說就是把Python的資料型別(字典,元組,列表)轉為str的資料型別過程。

反序列化:就是str的資料型別轉為Python物件的過程。

 

1.列表的序列化與反序列化(列表的序列化之後是str,反序列化之後是還是list)

import json
"""列表的序列化與反序列化"""
 list1=["go","java","python"]
 list_str=json.dumps(list1)
 print(list_str)
 print(type(list_str))

str_list
=json.loads(list_str) print(str_list) print(type(str_list))

 

 2.元組的序列化與反序列化(元組序列化之後是str,反序列化之後是list)

import json
"""列表的序列化與反序列化"""
list1=["go","java","python"]
list_str=json.dumps(list1)
print(list_str)
print(type(list_str))

str_list=json.loads(list_str)
print(str_list)
print(type(str_list))

 

 3.字典的序列化與反序列化(字典序列化之後是str,反序列化之後還是字典)

"""字典"""
dict1={"name":"李敏","age":20}
dict_str=json.dumps((dict))
print(dict_str)
str_dict=json.loads(dict_str)
print(str_dict)
print(type(str_dict))

 

 實戰:結構化輸出字典裡的內容

#indent=True:結構化輸出
#ensure_ascii=False:處理中文
print(json.dumps(dict,indent=True,ensure_ascii=False))

 

 

4.針對檔案的序列化和反序列化

#針對檔案的序列化和反序列化
#序列化:把目標檔案寫入檔案中
#encoding='utf-8'/ensure_ascii=False需要都寫中文才不會亂碼
json.dump(dict1,open("data.txt","w",encoding='utf-8'),ensure_ascii=False)

 

 

反序列化

#反序列化:從檔案裡面讀取檔案的內容
print(json.load(open('data.txt','r',encoding='utf-8')))