An introduction to some commonly used modules in Python
模块本质就是一个.py文件,在安装目录下的lib文件夹下可以看到
模块分为三个部分:内置模块(存在于解释器中),第三方模块(lib文件夹下),自定义模块(自己定义的)
1.time模块
import time#返回当前时间的时间戳print(time.time())#1498027773.1063557#以时间戳为参数,返回结构化的时间元组,参数默认为当前时间print(time.localtime(1912412470))#time.struct_time(tm_year=2030, tm_mon=8, tm_mday=8, tm_hour=17, tm_min=41, tm_sec=10, tm_wday=3, tm_yday=220, tm_isdst=0)#以时间戳为参数,返回结构化的格林尼治时间,默认参数为当前时间print(time.gmtime()) #time.struct_time(tm_year=2017, tm_mon=6, tm_mday=21, tm_hour=6, tm_min=49, tm_sec=2, tm_wday=2, tm_yday=172, tm_isdst=0)#结构化时间转化成字符串时间print(time.strftime('%Y:%m:%d-%X',time.localtime())) #2017:06:21-14:48:50#字符串时间转化为格式化时间print(time.strptime('1993-10-15','%Y-%m-%d')) #time.struct_time(tm_year=1993, tm_mon=10, tm_mday=15, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=4, tm_yday=288, tm_isdst=-1)#结构化时间转换成时间戳print(time.mktime(time.localtime()))#1498027859.0print(time.asctime()) #Wed Jun 21 14:53:11 2017print(time.ctime()) #Wed Jun 21 14:53:11 2017#线程推迟指定时间运行,参数为指定的秒数time.sleep(5)
几种时间形式的转换:
2.random模块
import randomprint(random.random())#随机返回一个(0,1)之间的浮点数 0.40165771797504246print(random.randint(1,3)) #随机返回一个指定范围[1,3]的int类型 3print(random.randrange(1,3)) #随机返回一个指定范围[1,3)的int类型 1print(random.choice([12,21,23,34,'a','b']))#随机返回一个指定列表中的元素 12print(random.sample([12,21,23,34,'a','b'],3))#随机返回指定个数的指定列表中的元素 ['a', 21, 'b']print(random.uniform(1,3))#随机返回一个(1,3)之间的浮点数 2.2162483038520144l=[1,2,3,4,5,6] random.shuffle(l) #把指定列表的顺序打乱print(l) #[1, 3, 6, 2, 4, 5]
练习
#练习,随机生成一个5位的验证码,包括数字,大小写字母import random res=''for i in range(5): num=random.randint(0,9) alpA=chr(random.randint(65,90)) alpa=chr(random.randint(97,122)) s=random.choice([str(num),alpA,alpa]) res=res+sprint(res)
3.os模块
1 import os 2 3 #获取当前工作目录 4 print(os.getcwd()) #C:\untitled\0621day12 5 6 #改变当前工作目录,相当于shell中的cd 7 os.chdir(file_path) 8 9 #生成多层递归目录10 os.makedirs('dirname1/dirname2')11 12 #递归删除空目录13 os.removedirs(path)14 15 #生成单级目录16 os.mkdir('dirname')17 18 #删除单级空目录,目录不为空则不能删除19 os.rmdir(path)20 21 #列出指定目录下的所有文件和子目录,包括隐藏文件,以列表方式打印22 print(os.listdir(r'C:\untitled\0612Python第五天')) #['0612作业.py', 'a.txt', '作业题目', '字符编码.py', '文件操作.py']23 24 #删除一个文件25 os.remove()26 27 #重命名文件/目录28 os.rename('oldname','newname')29 30 #获取文件/目录信息31 os.stat(path)32 print(os.stat(r'C:\untitled\0612Python第五天')) #os.stat_result(st_mode=16895, st_ino=2814749767244350, st_dev=3504670893, st_nlink=1, st_uid=0, st_gid=0, st_size=4096, st_atime=1497356489, st_mtime=1497356489, st_ctime=1497227714)33 34 #返回文件目录,其实就是os.path.split(path)的第一个元素35 os.path.dirname(path)36 37 #返回文件的文件名,其实就是os.path.split(path)的第二个元素38 os.path.basename(path)#如果path以/或\结尾,则会返回空值39 40 #如果文件存在,则返回True,否则返回False41 os.path.exists(path)42 43 #如果path是绝对路径,则返回True44 os.path.isabs(path)45 46 #将多个路径组合后返回,第一个绝对路径之前的参数将会被忽略47 os.path.join(path,paths)48 49 #返回path所指向的文件或目录的最后访问时间50 os.path.getatimme(path)51 52 #返回path所指向的文件或目录的最后修改时间53 os.path.getmtime(path)54 55 #返回path的大小56 os.path.getsize(path)
4.hashlib
hashlib模块提供了常见的摘要算法,如MD5,SHA1等,在Python3中,hash直接代替了MD5和SHA
摘要算法是通过一个函数,把任意长度的数据转成一个长度固定的数据串。
1.摘要算法是不可逆的,不能由数据串反推得到元数据
2.两个数据,即使只有1bit的区别,得到的摘要也是没有任何关系的
3.无论元数据有多大,得到的摘要都是固定长度的
4.当元数据很大时,需要一行一行去读,然后一行一行的校验,最后一个.hexdigest()能把之前所有的校验结果得到一个摘要
MD5速度很快,也很常用,生成结果是固定的128bit的通常由一个32位的16进制字符串表示。
import hashlib md5=hashlib.md5() md5.update('aasg'.encode('utf-8'))#434c591c9c5a04e44ec8dbafe81058e7md5.update('adasdg'.encode('utf-8'))#d20a55b2194493fdeb66e2cd358dab15md5.update('aasgadasdg'.encode('utf8'))#d20a55b2194493fdeb66e2cd358dab15print(md5.hexdigest())
未完待续。。。。
The above is the detailed content of An introduction to some commonly used modules in Python. For more information, please follow other related articles on the PHP Chinese website!

Python is an interpreted language, but it also includes the compilation process. 1) Python code is first compiled into bytecode. 2) Bytecode is interpreted and executed by Python virtual machine. 3) This hybrid mechanism makes Python both flexible and efficient, but not as fast as a fully compiled language.

Useaforloopwheniteratingoverasequenceorforaspecificnumberoftimes;useawhileloopwhencontinuinguntilaconditionismet.Forloopsareidealforknownsequences,whilewhileloopssuitsituationswithundeterminediterations.

Pythonloopscanleadtoerrorslikeinfiniteloops,modifyinglistsduringiteration,off-by-oneerrors,zero-indexingissues,andnestedloopinefficiencies.Toavoidthese:1)Use'i

Forloopsareadvantageousforknowniterationsandsequences,offeringsimplicityandreadability;whileloopsareidealfordynamicconditionsandunknowniterations,providingcontrolovertermination.1)Forloopsareperfectforiteratingoverlists,tuples,orstrings,directlyacces

Pythonusesahybridmodelofcompilationandinterpretation:1)ThePythoninterpretercompilessourcecodeintoplatform-independentbytecode.2)ThePythonVirtualMachine(PVM)thenexecutesthisbytecode,balancingeaseofusewithperformance.

Pythonisbothinterpretedandcompiled.1)It'scompiledtobytecodeforportabilityacrossplatforms.2)Thebytecodeistheninterpreted,allowingfordynamictypingandrapiddevelopment,thoughitmaybeslowerthanfullycompiledlanguages.

Forloopsareidealwhenyouknowthenumberofiterationsinadvance,whilewhileloopsarebetterforsituationswhereyouneedtoloopuntilaconditionismet.Forloopsaremoreefficientandreadable,suitableforiteratingoversequences,whereaswhileloopsoffermorecontrolandareusefulf

Forloopsareusedwhenthenumberofiterationsisknowninadvance,whilewhileloopsareusedwhentheiterationsdependonacondition.1)Forloopsareidealforiteratingoversequenceslikelistsorarrays.2)Whileloopsaresuitableforscenarioswheretheloopcontinuesuntilaspecificcond


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver CS6
Visual web development tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Mac version
God-level code editing software (SublimeText3)
