主頁 > 知識(shí)庫 > python常見模塊與用法

python常見模塊與用法

熱門標(biāo)簽:浙江電銷卡外呼系統(tǒng)好用嗎 地圖標(biāo)注微信發(fā)送位置不顯示 上海機(jī)器人外呼系統(tǒng)哪家好 地圖制圖標(biāo)注位置改變是移位嗎 南京銷售外呼系統(tǒng)軟件 房產(chǎn)電銷外呼系統(tǒng) 地圖標(biāo)注的意義點(diǎn) 315電話機(jī)器人廣告 蓋州市地圖標(biāo)注

一、常見內(nèi)置模塊

1.1什么叫做模塊?

import XXXX
xxxxx就是模塊 .py

1.2模塊的分類

1.random
2.math
3.內(nèi)置模塊

1.3第三方的模塊(需要安裝)

在線安裝 cmd 窗口下通過 pip install 模塊名
python -m pip install 模塊的名

離線安裝 下載好所需要的安裝包 zip ---- 解壓安裝包 ------setup.py--------cmd : python install
setup.py

二、模塊導(dǎo)入的問題

import 模塊名

import random

import 模塊名 as 別名

import random as r

from 包 import 模塊的名稱

from os import path

三、random模塊

用來產(chǎn)生隨機(jī)數(shù)(偽隨機(jī)數(shù))

[ ‘BPF', ‘LOG4', ‘NV_MAGICCONST', ‘RECIP_BPF', ‘Random', ‘SG_MAGICCONST', ‘SystemRandom',‘TWOPI', ‘Sequence', ‘Set', ‘a(chǎn)ll', ‘builtins', ‘cached', ‘doc', ‘file', ‘loader', ‘name', ‘package', ‘spec',‘a(chǎn)ccumulate', ‘a(chǎn)cos', ‘bisect', ‘ceil', ‘cos', ‘e', ‘exp', ‘floor', ‘inst', ‘log', ‘os', ‘pi', ‘random', ‘repeat', ‘sha512',‘sin', ‘sqrt', ‘test', ‘test_generator', ‘urandom', ‘_warn', ‘betavariate', ‘choice', ‘choices', ‘expovariate',‘gammavariate', ‘gauss', ‘getrandbits', ‘getstate', ‘lognormvariate', ‘normalvariate', ‘paretovariate',‘randbytes', ‘randint', ‘random', ‘randrange', ‘sample', ‘seed', ‘setstate', ‘shuffle', ‘triangular',‘uniform', ‘vonmisesvariate', ‘weibullvariate' ]

主要常見的random模塊的函數(shù):

3.1randint() --------- 產(chǎn)生隨機(jī)整數(shù)[m,n]

3.2random() --------------產(chǎn)生0-1的隨機(jī)數(shù)[0,1)

3.3uniform() ------------- 產(chǎn)生正態(tài)分布的隨機(jī)數(shù)

3.4randrange() ------ 產(chǎn)生一個(gè)范圍內(nèi)的隨機(jī)數(shù)

3.5choices() ---------- 用在序列(容器)(有序的序列)隨機(jī)篩取一個(gè)元素

四、math模塊

用于數(shù)學(xué)運(yùn)算

[‘doc', ‘loader', ‘name', ‘package', ‘spec', ‘a(chǎn)cos', ‘a(chǎn)cosh', ‘a(chǎn)sin', ‘a(chǎn)sinh', ‘a(chǎn)tan', ‘a(chǎn)tan2', ‘a(chǎn)tanh',
‘ceil', ‘comb', ‘copysign', ‘cos', ‘cosh', ‘degrees', ‘dist', ‘e', ‘erf', ‘erfc', ‘exp', ‘expm1', ‘fabs', ‘factorial',
‘floor', ‘fmod', ‘frexp', ‘fsum', ‘gamma', ‘gcd', ‘hypot', ‘inf', ‘isclose', ‘isfinite', ‘isinf', ‘isnan', ‘isqrt',
‘lcm', ‘ldexp', ‘lgamma', ‘log', ‘log10', ‘log1p', ‘log2', ‘modf', ‘nan', ‘nextafter', ‘perm', ‘pi', ‘pow',
‘prod', ‘radians', ‘remainder', ‘sin', ‘sinh', ‘sqrt', ‘tan', ‘tanh', ‘tau', ‘trunc', ‘ulp']

ceil ------------- 向上取整
floor ----------- 向下取整
e ------------ 屬性 自然常數(shù)
fabs ----------- 求絕對(duì)值 等價(jià) abs() 全局函數(shù)
fmod ----------- 求模運(yùn)算
isnan -------- 判斷是不是數(shù)字 (是數(shù)字返回 false nan -----not a number)
isfinite ----- 判斷是不是無限
pi ----------- 圓周率
pow ------------- 冪次方
sqrt ---------- 平方根

五、os模塊

5.1操作系統(tǒng)文件

清屏的方法 --------- import os os.system(“cls”)

[‘DirEntry', ‘F_OK', ‘GenericAlias', ‘Mapping', ‘MutableMapping', ‘O_APPEND', ‘O_BINARY',
‘O_CREAT', ‘O_EXCL', ‘O_NOINHERIT', ‘O_RANDOM', ‘O_RDONLY', ‘O_RDWR', ‘O_SEQUENTIAL',
‘O_SHORT_LIVED', ‘O_TEMPORARY', ‘O_TEXT', ‘O_TRUNC', ‘O_WRONLY', ‘P_DETACH', ‘P_NOWAIT',‘P_NOWAITO', ‘P_OVERLAY', ‘P_WAIT', ‘PathLike', ‘R_OK', ‘SEEK_CUR', ‘SEEK_END', ‘SEEK_SET',‘TMP_MAX', ‘W_OK', ‘X_OK', ‘AddedDllDirectory', ‘Environ', ‘a(chǎn)ll', ‘builtins', ‘cached', ‘doc', ‘file',‘loader', ‘name', ‘package', ‘spec', ‘check_methods', ‘execvpe', ‘exists', ‘exit', ‘fspath',
‘get_exports_list', ‘walk', ‘wrap_close', ‘a(chǎn)bc', ‘a(chǎn)bort', ‘a(chǎn)ccess', ‘a(chǎn)dd_dll_directory', ‘a(chǎn)ltsep', ‘chdir',
‘chmod', ‘close', ‘closerange', ‘cpu_count', ‘curdir', ‘defpath', ‘device_encoding', ‘devnull', ‘dup',
‘dup2', ‘environ', ‘error', ‘execl', ‘execle', ‘execlp', ‘execlpe', ‘execv', ‘execve', ‘execvp', ‘execvpe',
‘extsep', ‘fdopen', ‘fsdecode', ‘fsencode', ‘fspath', ‘fstat', ‘fsync', ‘ftruncate', ‘get_exec_path',
‘get_handle_inheritable', ‘get_inheritable', ‘get_terminal_size', ‘getcwd', ‘getcwdb', ‘getenv',
‘getlogin', ‘getpid', ‘getppid', ‘isatty', ‘kill', ‘linesep', ‘link', ‘listdir', ‘lseek', ‘lstat', ‘makedirs', ‘mkdir',
‘name', ‘open', ‘pardir', ‘path', ‘pathsep', ‘pipe', ‘popen', ‘putenv', ‘read', ‘readlink', ‘remove',
‘removedirs', ‘rename', ‘renames', ‘replace', ‘rmdir', ‘scandir', ‘sep', ‘set_handle_inheritable',
‘set_inheritable', ‘spawnl', ‘spawnle', ‘spawnv', ‘spawnve', ‘st', ‘startfile', ‘stat', ‘stat_result',
‘statvfs_result', ‘strerror', ‘supports_bytes_environ', ‘supports_dir_fd', ‘supports_effective_ids',
‘supports_fd', ‘supports_follow_symlinks', ‘symlink', ‘sys', ‘system', ‘terminal_size', ‘times',
‘times_result', ‘truncate', ‘umask', ‘uname_result', ‘unlink', ‘unsetenv', ‘urandom', ‘utime', ‘waitpid',
‘waitstatus_to_exitcode', ‘walk', ‘write']

5.2os模塊常用方法

chdir() ------- 修改工作目錄
curdir ------- 獲取當(dāng)前的目錄 返回的結(jié)果的是相對(duì)路徑 (絕對(duì)路徑 os.path.abspath(os.curdir) )
chmod() ---------修改權(quán)限
close -------- 關(guān)閉文件的路徑
cpu_count() --------- 返回的cpu的核對(duì)應(yīng)得線程數(shù)
getcwd() ----------獲取當(dāng)前路徑,返回得是絕對(duì)路徑,相當(dāng)linux下pwd
getpid()-------獲取當(dāng)前進(jìn)程的進(jìn)程編號(hào)
getppid() ------------獲取當(dāng)前進(jìn)程的父進(jìn)程的進(jìn)程編號(hào)
kill() ------------- 通過進(jìn)程編號(hào)殺死進(jìn)程
linesep -------- 屬性 對(duì)應(yīng)系統(tǒng)下的換行符
listdir() ------ 返回的對(duì)應(yīng)目錄下所有的文件和文件夾(隱藏的文件夾),返回的是列表
makedirs() ----- 創(chuàng)建目錄,支持多層目錄的創(chuàng)建
mkdir() ----- 創(chuàng)建目錄,只能創(chuàng)建一層,不支持多層
open()------創(chuàng)建文件 open()全局函數(shù)
pathsep ------- 獲取環(huán)境變量分隔符 windows ; linux分割符 :
sep --------- 獲取路徑分割符
remove(文件名或者路徑) ----------刪除文件
removedirs() --------------- 刪除目錄,支持多級(jí)刪除(遞歸)
system()-------- 執(zhí)行終端命令

5.3os.path模塊

import os.path
import os.path as p
from os import path

[‘a(chǎn)ll', ‘builtins', ‘cached', ‘doc', ‘file', ‘loader', ‘name', ‘package', ‘spec', ‘a(chǎn)bspath_fallback',
‘get_bothseps', ‘getfinalpathname', ‘getfinalpathname_nonstrict', ‘getfullpathname',
‘getvolumepathname', ‘nt_readlink', ‘readlink_deep', ‘a(chǎn)bspath', ‘a(chǎn)ltsep', ‘basename', ‘commonpath',
‘commonprefix', ‘curdir', ‘defpath', ‘devnull', ‘dirname', ‘exists', ‘expanduser', ‘expandvars', ‘extsep',
‘genericpath', ‘getatime', ‘getctime', ‘getmtime', ‘getsize', ‘isabs', ‘isdir', ‘isfile', ‘islink', ‘ismount',
‘join', ‘lexists', ‘normcase', ‘normpath', ‘os', ‘pardir', ‘pathsep', ‘realpath', ‘relpath', ‘samefile',
‘sameopenfile', ‘samestat', ‘sep', ‘split', ‘splitdrive', ‘splitext', ‘stat', ‘supports_unicode_filenames',
‘sys']

abspath(相對(duì)路徑) ----------------- 返回的路徑的所對(duì)應(yīng)的絕對(duì)路徑
altsep ------------------ 返回的python中的分隔符
basename ------------ 文件名稱
dirname ----------- 文件目錄
exists ---------------- 判斷文件或者目錄是否存在
getctime -------- 獲取時(shí)間(創(chuàng)建時(shí)間)
getmtime ------------ 獲取修改時(shí)間
getsize ------------ 獲取文件的大小,單位是字節(jié)
isdir-------------- 判斷path是否是目錄(文件夾)
isfile-------------------判斷path是否是文件
isabs ------------- 判斷是不是絕對(duì)路徑
islink ------- 判斷是不是鏈接
ismount ---------- 判斷是不是掛載文件
join -------------- 拼接路徑
sep ----------- 路徑分隔符
split ----------分割路徑
relpath ------------- 返回的真正的路徑和abspath一樣

5.4練習(xí)

需要結(jié)合os.path 和 os 模塊,以及函數(shù)的遞歸

給出一個(gè)路徑,遍歷當(dāng)前路徑所有文件和文件夾,打印出所有的文件(遇到文件輸出路徑,如果遇
到的文件夾繼續(xù)遍歷文件夾)

import os
from os import path
def scanner_file(url):
    files = os.listdir(url)
    #拼接路徑
    for file in files:
        #real_path = url + "\\" + f
        real_path = path.join(url,file)
        #print (file)
        if path.isfile(real_path):
            l = path.abspath(real_path) # 把取出來的路徑賦值給L
            print(l)#輸出在屏幕上
        elif path.isdir(real_path):
            scanner_file(real_path)
        else:
            print("其他情況")
            pass
scanner_file("E:\\")

六、sys模塊

[‘breakpointhook', ‘displayhook', ‘doc', ‘excepthook', ‘interactivehook', ‘loader', ‘name',
‘package', ‘spec', ‘stderr', ‘stdin', ‘stdout', ‘unraisablehook', ‘base_executable', ‘clear_type_cache',
‘current_frames', ‘debugmallocstats', ‘enablelegacywindowsfsencoding', ‘framework', ‘getframe', ‘git',
‘home', ‘xoptions', ‘a(chǎn)ddaudithook', ‘a(chǎn)pi_version', ‘a(chǎn)rgv', ‘a(chǎn)udit', ‘base_exec_prefix', ‘base_prefix',
‘breakpointhook', ‘builtin_module_names', ‘byteorder', ‘call_tracing', ‘copyright', ‘displayhook',
‘dllhandle', ‘dont_write_bytecode', ‘exc_info', ‘excepthook', ‘exec_prefix', ‘executable', ‘exit', ‘flags',
‘float_info', ‘float_repr_style', ‘get_asyncgen_hooks', ‘get_coroutine_origin_tracking_depth',
‘getallocatedblocks', ‘getdefaultencoding', ‘getfilesystemencodeerrors', ‘getfilesystemencoding',
‘getprofile', ‘getrecursionlimit', ‘getrefcount', ‘getsizeof', ‘getswitchinterval', ‘gettrace',
‘getwindowsversion', ‘hash_info', ‘hexversion', ‘implementation', ‘int_info', ‘intern', ‘is_finalizing',
‘maxsize', ‘maxunicode', ‘meta_path', ‘modules', ‘path', ‘path_hooks', ‘path_importer_cache',
‘platform', ‘platlibdir', ‘prefix', ‘ps1', ‘ps2', ‘pycache_prefix', ‘set_asyncgen_hooks'
‘set_coroutine_origin_tracking_depth', ‘setprofile', ‘setrecursionlimit', ‘setswitchinterval', ‘settrace',
‘stderr', ‘stdin', ‘stdout', ‘thread_info', ‘unraisablehook', ‘version', ‘version_info', ‘warnoptions',
‘winver']

api_version -------------- 屬性 獲取python內(nèi)部的版本號(hào)
argv --------- 接收腳本參數(shù)
copyright ------------ 輸出cpython版本號(hào)
exit ---------- 退出系統(tǒng)
getdefaultencoding()-------------獲取的默認(rèn)編碼,python3默認(rèn)編碼是utf-8
getfilesystemencoding()------------ 獲取文件系統(tǒng)的默認(rèn)編程,默認(rèn)utf-8
getrecursionlimit()------- 獲取python對(duì)遞歸的限制層數(shù)
setrecursionlimit() -------------重新設(shè)置遞歸的限制的層數(shù)
getrefcount(對(duì)象)--------- 獲取對(duì)象的引用計(jì)數(shù),是垃圾回收機(jī)制里的引用計(jì)數(shù),注意任何對(duì)象都
有一個(gè)默認(rèn)引用計(jì)數(shù)
getwindowsversion() ---------- 獲取當(dāng)前窗口的版本信息
version -----------## 標(biāo)題-- 獲取版本信息

**python的垃圾回收機(jī)制:

以引用計(jì)數(shù)為主,以標(biāo)記清除和分代收集為輔
Java 以標(biāo)記清除為主,以引用計(jì)數(shù)和分代收集為輔 **

七、時(shí)間模塊

 7.1time模塊

python提供操作日期和時(shí)間的模塊

['_STRUCT_TM_ITEMS', ‘doc', ‘loader', ‘name', ‘package', ‘spec', ‘a(chǎn)ltzone', ‘a(chǎn)sctime', ‘ctime',
‘daylight', ‘get_clock_info', ‘gmtime', ‘localtime', ‘mktime', ‘monotonic', ‘monotonic_ns',
‘perf_counter', ‘perf_counter_ns', ‘process_time', ‘process_time_ns', ‘sleep', ‘strftime', ‘strptime',
‘struct_time', ‘thread_time', ‘thread_time_ns', ‘time', ‘time_ns', ‘timezone', ‘tzname']

asctime() ------------ 獲取當(dāng)前時(shí)間
ctime()------ 獲取當(dāng)前時(shí)間
localtime()------ 獲取的本地時(shí)間,返回的是對(duì)象
sleep()-------- 表示休眠的時(shí)間,單位秒
time()---------------- 獲取當(dāng)前系統(tǒng)的時(shí)間戳,單位也是秒
strftime()------- 將時(shí)間對(duì)象格式化成字符串
strptime()------將一個(gè)特定的時(shí)間字符串轉(zhuǎn)換為時(shí)間對(duì)象

7.2datetime模塊

對(duì)Time模塊的補(bǔ)充

from datetime import datetime
[‘a(chǎn)dd', ‘class', ‘delattr', ‘dir', ‘doc', ‘eq', ‘format', ‘ge', ‘getattribute', ‘gt', ‘hash', ‘init',
‘init_subclass', ‘le', ‘lt', ‘ne', ‘new', ‘radd', ‘reduce', ‘reduce_ex', ‘repr', ‘rsub', ‘setattr', ‘sizeof',
‘str', ‘sub', ‘subclasshook', ‘a(chǎn)stimezone', ‘combine', ‘ctime', ‘date', ‘day', ‘dst', ‘fold',
‘fromisocalendar', ‘fromisoformat', ‘fromordinal', ‘fromtimestamp', ‘hour', ‘isocalendar',
‘isoformat', ‘isoweekday', ‘max', ‘microsecond', ‘min', ‘minute', ‘month', ‘now', ‘replace', ‘resolution',
‘second', ‘strftime', ‘strptime', ‘time', ‘timestamp', ‘timetuple', ‘timetz', ‘today', ‘toordinal', ‘tzinfo',
‘tzname', ‘utcfromtimestamp', ‘utcnow', ‘utcoffset', ‘utctimetuple', ‘weekday', ‘year']

now() ------------獲取當(dāng)前的時(shí)間

八、其他模塊

日歷的模塊(calendar)

uuid 模塊 ------------ 一般會(huì)用在文件上傳或者文件備份的時(shí)候:

產(chǎn)生一個(gè)永不重復(fù)的字符串
uuid.uuid4().hex

練習(xí):完成用戶注冊(cè)登錄的案例(加鹽值混淆)

import sys
import hashlib
users=[]
salt = "#!@$@!%^#^!!##@!"
def main():
    print("*~"*20)
    print("1.用戶注冊(cè)")
    print("2.用戶登錄")
    print("3.退出系統(tǒng)")
    print("*~"*20)
    choice = input("請(qǐng)選擇對(duì)應(yīng)想要的操作:")
    return choice

def register():
    username = input("請(qǐng)輸入注冊(cè)用戶名:")
    passwd = input("請(qǐng)輸入注冊(cè)用戶密碼:")
    if username == None or username.strip() == "":
        print("用戶名不能為空")
        return
    if passwd == None or passwd.strip()=="" or len(passwd)  6:
        print("用戶密碼不能為空或者小于6位長度")
        return
    passwd = passwd_md5(passwd)
    for i in users:
        if i.get("username") == username:
            print("用戶名重復(fù)")
            return
    user = {}
    user["username"] = username
    user["passwd"] = passwd
    users.append(user)
    print(users)

def passwd_md5(passwd):
    md5 = hashlib.md5(passwd.encode("utf-8"))
    md5.update(salt.encode("utf-8"))
    return md5.hexdigest()

def is_login(username,passwd):
    for i in users:
        if i.get("username") == username and i.get("passwd") == passwd:
            return True
        return False

def login():
    username = input("請(qǐng)輸入登陸的用戶名:")
    passwd = input("請(qǐng)輸入登陸用戶密碼:")
    passwd = passwd_md5(passwd)
    if is_login(username,passwd):
        print("恭喜,登陸成功")
        print(users) /
    else:
        print("抱歉,登陸失敗")

while(True):
    choice = main()
    if choice == "1":
        print("注冊(cè)")
        register()
    elif choice =="2":
        print("登陸")
        login()
    elif choice =="3":
        print("退出系統(tǒng)......")
        sys.exit()

九、加密算法的介紹

有了解加密? 加密是計(jì)算機(jī)中最重要的技術(shù)之一

分類:

以算法的是否可逆:

可逆算法

是不是使用同一密鑰:

對(duì)稱加密

解密和加密的時(shí)候使用同一個(gè)密鑰
DES算法

不對(duì)稱加密

加密和解密使用的是同一對(duì)密鑰(公鑰、私鑰)https協(xié)議 RSA算法

不可逆算法(hash算法)

特點(diǎn):不可逆、結(jié)果是唯一的

MD5

十、hashlib庫

10.1哈希算法

import hashlib

使用步驟:

創(chuàng)建算法對(duì)象(md5 sha256),返回的是算法對(duì)象
md5 = hashlib.md5()
md5
一個(gè)字符串加密的話md5 = hashlib.md5(“123”.encode(“utf-8”))
如果不做鹽值混淆, md5.hexdigest()

鹽值混淆

md5.update(鹽值)

鹽值越復(fù)雜,加密的安全性就越高

cmd5.com 解密

10.2hmac庫

也是一個(gè)哈希加密庫,用到了對(duì)稱加密
new()
參數(shù):第一個(gè)參數(shù)是要加密的字符串,第二個(gè)參數(shù)鹽值,第三個(gè)參數(shù)是加密算法
首先使用對(duì)稱加密(密鑰就是鹽值),得到加密的結(jié)果之后又進(jìn)行了一次hash加密(鹽值混淆)

十一、對(duì)象序列化

什么是對(duì)象序列化?

字典 列表 元組 集合 -------------- 對(duì)象

序列化:將抽象的這些對(duì)象的概念轉(zhuǎn)換真正的字符或者字節(jié)數(shù)據(jù)

十二、pickle模塊

[‘ADDITEMS', ‘APPEND', ‘APPENDS', ‘BINBYTES', ‘BINBYTES8', ‘BINFLOAT', ‘BINGET', ‘BININT',
‘BININT1', ‘BININT2', ‘BINPERSID', ‘BINPUT', ‘BINSTRING', ‘BINUNICODE', ‘BINUNICODE8', ‘BUILD',‘BYTEARRAY8', ‘DEFAULT_PROTOCOL', ‘DICT', ‘DUP', ‘EMPTY_DICT', ‘EMPTY_LIST', ‘EMPTY_SET',‘EMPTY_TUPLE', ‘EXT1', ‘EXT2', ‘EXT4', ‘FALSE', ‘FLOAT', ‘FRAME', ‘FROZENSET', ‘FunctionType', ‘GET',‘GLOBAL', ‘HIGHEST_PROTOCOL', ‘INST', ‘INT', ‘LIST', ‘LONG', ‘LONG1', ‘LONG4', ‘LONG_BINGET',‘LONG_BINPUT', ‘MARK', ‘MEMOIZE', ‘NEWFALSE', ‘NEWOBJ', ‘NEWOBJ_EX', ‘NEWTRUE',‘NEXT_BUFFER', ‘NONE', ‘OBJ', ‘PERSID', ‘POP', ‘POP_MARK', ‘PROTO', ‘PUT', ‘PickleBuffer',‘PickleError', ‘Pickler', ‘PicklingError', ‘PyStringMap', ‘READONLY_BUFFER', ‘REDUCE', ‘SETITEM',‘SETITEMS', ‘SHORT_BINBYTES', ‘SHORT_BINSTRING', ‘SHORT_BINUNICODE', ‘STACK_GLOBAL',‘STOP', ‘STRING', ‘TRUE', ‘TUPLE', ‘TUPLE1', ‘TUPLE2', ‘TUPLE3', ‘UNICODE', ‘Unpickler',‘UnpicklingError', ‘Framer', ‘HAVE_PICKLE_BUFFER', ‘Pickler', ‘Stop', ‘Unframer', ‘Unpickler', ‘a(chǎn)ll',‘builtins', ‘cached', ‘doc', ‘file', ‘loader', ‘name', ‘package', ‘spec', ‘compat_pickle', ‘dump', ‘dumps',‘extension_cache', ‘extension_registry', ‘getattribute', ‘inverted_registry', ‘load', ‘loads', ‘test',
‘_tuplesize2code', ‘bytes_types', ‘codecs', ‘compatible_formats', ‘decode_long', ‘dispatch_table',
‘dump', ‘dumps', ‘encode_long', ‘format_version', ‘io', ‘islice', ‘load', ‘loads', ‘maxsize', ‘pack',
‘partial', ‘re', ‘sys', ‘unpack', ‘whichmodule']

dumps -------------- 將對(duì)象序列化為字節(jié)數(shù)據(jù) .dat

loads -------------- 將數(shù)據(jù)反序列化為對(duì)象

users = [1,2,3,4,5]
data = pickle.dumps(users) # 將對(duì)象序列化
    f = open("a.txt","wb")
    f.write(data)
    f.close()
    f = open("a.dat","wb")
    f.write(data)
    f.close()
    f = open("a.dat","rb")
    show = f.read()
    print(data,"\n")
    print("對(duì)象序列化為字節(jié)數(shù)據(jù):",show,"\n")
    print("將數(shù)據(jù)反序列化為對(duì)象:",pickle.loads(show),"\n")  #將數(shù)據(jù)反序列化為對(duì)象

dump --------------將對(duì)象序列化為字節(jié)數(shù)據(jù) ,并且保存到file

load -------------- 將數(shù)據(jù)反序列化為對(duì)象

十三、json模塊

Python2只能操作字典對(duì)象

dumps -------------- 將對(duì)象序列化為字節(jié)數(shù)據(jù) .dat

loads -------------- 將數(shù)據(jù)反序列化為對(duì)象

dump --------------將對(duì)象序列化為字節(jié)數(shù)據(jù) ,并且保存到file

load -------------- 將數(shù)據(jù)反序列化為對(duì)象

到此這篇關(guān)于python常見模塊與用法的文章就介紹到這了,更多相關(guān)python模塊用法內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

您可能感興趣的文章:
  • python copy模塊中的函數(shù)實(shí)例用法
  • Python多線程 Queue 模塊常見用法
  • Python中os模塊的實(shí)例用法
  • Python協(xié)程asyncio模塊的演變及高級(jí)用法
  • Python寫腳本常用模塊OS基礎(chǔ)用法詳解
  • python 中os模塊os.path.exists()的用法說明
  • python re模塊常見用法例舉
  • 詳解Python中openpyxl模塊基本用法
  • Python常用的模塊和簡單用法

標(biāo)簽:雙鴨山 克拉瑪依 臨汾 日照 陽泉 赤峰 金華 貴州

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《python常見模塊與用法》,本文關(guān)鍵詞  python,常見,模塊,與,用法,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。
  • 相關(guān)文章
  • 下面列出與本文章《python常見模塊與用法》相關(guān)的同類信息!
  • 本頁收集關(guān)于python常見模塊與用法的相關(guān)信息資訊供網(wǎng)民參考!
  • 推薦文章