Python basis (nine) Common Module Summary

3.8 json module focus

json module data structure is converted to meet the conditions of particular string, and may also deserialize restored back.

  • A data follow a different language format conversion, i.e. a special strings of different languages ​​are used. (Such as a Python list [1, 2, 3] using a special character string is converted into json, and then sent to the developer php encoded into bytes, the developer can php decoded into a particular string, and then in the reverse Solutions to the source array (list): [1, 2, 3])
  • json serialization support only part of the data structure Python: dict, list, tuple, str, int, float, True, False, None

For network transmission, read and write file: dumps (converted into str) loads (turned back)

network transmission

import json                     #导入json模块
dic={1:'李文浩',2:'聂冰',3:'赵秋雨'}
new_dic=json.dumps(dic,ensure_ascii=False)          #将dict格式转化成str格式
print(new_dic,type(new_dic)#{"1": "李文浩", "2": "聂冰", "3": "赵秋雨"} <class 'str'>
old_b=old_dic.encode('utf-8')       #将str模式的字典转化成byts类型编码
    #模拟网络传输
    new_b=old_b.decode('utf-8')     #解码
new_dic=json.loads(new_b)           #转化成字典类型
print(new_dic,type(new_dic))

File Write

  • Write a single line
import json
dic={1:'李文浩',2:'聂冰',3:'赵秋雨'}
with open('json测试.json',mode='w',encoding='utf-8')as f1:
    old_dic=json.dumps(dic,ensure_ascii=False)
    f1.write(old_dic)
with open('json测试.json',encoding='utf-8')as f2:
    print(json.loads(f2.read()))
  • Write multiple lines
dic1 = {'name':'oldboy1'}
dic2 = {'name':'oldboy2'}
dic3 = {'name':'oldboy3'}
f = open('序列化',encoding='utf-8',mode='a')
str1 = json.dumps(dic1)
f.write(str1+'\n')
str2 = json.dumps(dic2)
f.write(str2+'\n')
str3 = json.dumps(dic3)
f.write(str3+'\n')
f.close()
​
f = open('序列化',encoding='utf-8')
for line in f:
    print(json.loads(line))

For a single data file write read: dump, load

import json
f = open('json_file.json','w')
dic = {'k1':'v1','k2':'v2','k3':'v3'}
json.dump(dic,f)  #dump方法接收一个文件句柄,直接将字典转换成json字符串写入文件
f.close()
# json文件也是文件,就是专门存储json字符串的文件。
f = open('json_file.json')
dic2 = json.load(f)  #load方法接收一个文件句柄,直接将文件中的json字符串转换成数据结构返回
f.close()
print(type(dic2),dic2)

3.9 pickle module

For network transmission: dumps, loads

import pickle
dic={1:'李文浩',2:'聂冰',3:'赵秋雨'}
str_dic=pickle.dumps(dic)
print(str_dic)          #bytes类型
dic2=pickle.loads(str_dic)
print(dic2)             #dict类型 

Used to write the document read: dump, load

dic = {(1,2):'oldboy',1:True,'set':{1,2,3}}
f = open('pick序列化',mode='wb')
pickle.dump(dic,f)
f.close()
with open('pick序列化',mode='wb') as f1:
    pickle.dump(dic,f1)

3.9 os module

os.getcwd()     # 获取当前工作目录,即当前python脚本工作的目录路径
os.chdir("dirname")  改变当前脚本工作目录;相当于shell下cd  **
os.curdir  返回当前目录: ('.')  **
os.pardir  获取当前目录的父目录字符串名:('..') **

And folders related

os.makedirs('dirname1/dirname2')    #递归生成目录  ***
os.removedirs('dirname1')           #递归删除目录(目录里没有文件(为空)才可以删除)
os.mkdir('绝对路径/相对路径')          #创建一个文件夹 ***
os.rmdir('绝对路径/相对路径')          #删除文件夹***
os.listdir('dirname')               $列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表打印

And related documents

os.remove()  $删除一个文件  ***
os.rename("oldname","newname")  $重命名文件/目录  ***
os.stat('path/filename')  获取文件/目录信息 **

path series, and path-related

os.path.abspath(path) $返回path规范化的绝对路径  ***
os.path.split(path)   #将path分割成目录和文件名二元组返回 ***
os.path.dirname('E:\Python项目')# E:\        获取父级目录
os.path.dirname(os.path.dirname(__file__))#获取父级目录的父级目录 :获取爷爷级目录
os.path.basename('E:\Python项目')#Python项目  返回文件名
os.path.exists(path)  #查看文件夹或文件是否存在存在,返回True;如果path不存在,返回False
os.path.isabs(path)   #如果path是绝对路径,返回True  **
os.path.isfile(path)  #如果path是一个存在的文件,返回True。否则返回False  ***
os.path.isdir(path)   #如果path是一个存在的目录,则返回True。否则返回False  ***
os.path.join('D:','s23','day20','随便')#路径拼接,第一个绝对路径之前的参数将被忽略 ***
os.path.getatime(path)  #返回path所指向的文件或者目录的最后访问时间  **
os.path.getmtime(path)  #返回path所指向的文件或者目录的最后修改时间  **
os.path.getsize(path)   #返回path的大小 ***
print(__file__)         $动态获取文件的绝对路径

4.0sys module

sys.argv           命令行参数List,第一个元素是程序本身路径
sys.exit(n)        退出程序,正常退出时exit(0),错误退出sys.exit(1)
sys.version        获取Python解释程序的版本信息
sys.path           返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值  ***
sys.platform       返回操作系统平台名称

4.1 hashlib module

Ordinary encryption

import hashlib
md5 = hashlib.md5()
md5.update('要加密的字符串'.encode('utf-8'))
print(md5.hexdigest())

Salt Encryption

  • Fixed salts
import hashlib
md5=hashlib.md5('盐'.encode('utf-8'))
md5.update('要加密的字符串'.encode('utf-8'))
print(md5.hexdigest())
  • Dynamics of salt
username = '太白金星666'
ret = hashlib.md5(username[::2].encode('utf-8'))  # 针对于每个账户,每个账户的盐都不一样
ret.update('a'.encode('utf-8'))
print(ret.hexdigest())

Consistency checking files

def md5_file(path):
    ret = hashlib.md5()
    with open(path,mode='rb') as f1:
        while 1:
            content = f1.read(1024)
            if content:
                ret.update(content)
            else:
                return ret.hexdigest()
print(md5_file(r'E:\Python项目\python-3.7.4rc1-embed-win32.zip'))

4.2time module

#导入时间模块
>>>import time

#时间戳
>>>time.time()
1500875844.800804

#时间字符串
>>>time.strftime("%Y-%m-%d %X")
'2017-07-24 13:54:37'
>>>time.strftime("%Y-%m-%d %H-%M-%S")
'2017-07-24 13-55-04'

#时间元组:localtime将一个时间戳转换为当前时区的struct_time
time.localtime()
time.struct_time(tm_year=2017, tm_mon=7, tm_mday=24,
          tm_hour=13, tm_min=59, tm_sec=37, 
                 tm_wday=0, tm_yday=205, tm_isdst=0)

4.3 Random Module

>>> import random
#随机小数
>>> random.random()      # 大于0且小于1之间的小数
0.7664338663654585
>>> random.uniform(1,3) #大于1小于3的小数
1.6270147180533838
#恒富:发红包

#随机整数
>>> random.randint(1,5)  # 大于等于1且小于等于5之间的整数
>>> random.randrange(1,10,2) # 大于等于1且小于10之间的奇数


#随机选择一个返回
>>> random.choice([1,'23',[4,5]])  # #1或者23或者[4,5]
#随机选择多个返回,返回的个数为函数的第二个参数
>>> random.sample([1,'23',[4,5]],2) # #列表元素任意2个组合
[[4, 5], '23']


#打乱列表顺序
>>> item=[1,3,5,7,9]
>>> random.shuffle(item) # 打乱次序
>>> item
[5, 1, 3, 7, 9]
>>> random.shuffle(item)
>>> item
[5, 9, 7, 1, 3]

Guess you like

Origin www.cnblogs.com/llwwhh/p/11139385.html