What is a module?
Related recommendations: "python video"
In the process of computer program development , as more and more program code is written, the code in a file will become longer and longer, and it will become less and less easy to maintain. In order to write maintainable code, we group many functions and put them in different files. In this way, each file contains relatively less code. Many programming languages adopt this way of organizing code. In python, a .py file is a module;
Use modules the benefits of?
1. The biggest benefit is that it greatly improves the maintainability of the code. Secondly, you don’t have to start from scratch when writing code. When a module is written, it can be referenced by other modules. We are When writing programs, we often reference other modules, including python built-in modules and modules from third parties.
2. Using modules can avoid conflicts between function names and variables. Each module has an independent namespace, so the same name The functions and variables can be in different modules, so when we write the module ourselves, we don’t have to consider that the name will conflict with other modules;
Module classification
Modules are divided into 3 categories:
1. Built-in standard module, also known as: standard library, execute (help'modules') to view the list of all python built-in modules;
2. Third-party open source modules can be installed online through pip install module name;
3. Custom module;
Call of module
import modulefrom module import xxfrom module.xx.xx import xx as rename from module.xx.xx import *
Note: Once the module is Calling is equivalent to executing the code in another py file;
time module
time.localtime([secs]): Convert a timestamp to If the struct_time and secs parameters of the current time zone are not provided, the current time shall prevail;
time.gmtime([secs]): Similar to the localtime() method, the gmtime() method converts a timestamp into struct_time in UTC time zone (0 time zone).
time.time(): Returns the timestamp of the current time
time.mktime(): Converts a struct_time into a timestamp
time.sleep(secs): The thread delays running for the specified time, in seconds
tiem.asctime([t]): Represents a time tuple or struct_time in this form: sun oct 1 12:04:38 2017, if Without parameters, time.localtime() will be passed in as a parameter;
time.ctime([secs]): Convert a timestamp (seconds) into the form of time.asctime(), if the parameter When not given, or is None, time.time() will be used as a parameter by default. Its function is equivalent to time.asctime(time.localtime(secs))
time.strftime(format[,t ]): Convert a tuple or struct_time representing time (such as returned by time.localtime() and time.gmtime()) into a formatted time string. If t is not specified, time.localtime will be passed in ()
datetime module
Compared with the time module, the datetime module has an intuitive interface and is easier to call;
The datetime module defines the following classes:
datetime.date: A class that represents date. Commonly used attributes are: year month, daydatetime.time: A class that represents time. Commonly used attributes are: hour, minute, second, microsecond. datetime.datetime: represents date and time.
datetime.timedelta: represents the time interval, that is, the length between two points in time
datetime.tzinfo Related information related to time zones
What we need to remember:
1.d=datetime.datetime.now() returns the current datetime date type
import datetime d=datetime.datetime。now() print(d) print(d.year) print(d.today()) print(d.timestamp()) print(d.timetuple())
and other methods can call
2.datetime.formtimestamp(322222) to convert a timestamp It is datetime date type;
datetime.date.fromtimestamp(time.time())
3. Time operation:
datetime.datetime.now()+datetime.timedelta(4)#当前时间+4天 datetime.datetime.now()+datetimetimedelta(hours=4)#当前时间+4小时
4. Time replacement
d=datetime.datetime.now() d.replace(year=2999,month=11,day=30) datetime.date(2999,11,30)
random random number
There are many places in the program where random characters need to be used, such as the verification code for logging into the website. Random strings can be easily generated through the random module
random.randrange(1,10)# Returns 1-10 A random number between 10random.randint(1,10)#Returns a random number between 1-10, including 10random.randrange(0,100,2)#Randomly selects an even number random between 0 and 100. random()#Returns a random floating point number random.choice('abc#$@1')#Returns a random character in a given data set random.sample('abcdefghij',3)#Select from multiple strings A specific number of characters
#Generate a random string
import string''.json(random.sample(string.ascii_lowercase string.digits,6))
#Shuffle
a=[0 ,1,2,3,4,5,6,7,8,9]random.shuffle(a)print(a)
sys module
1.sys.argv
python3 test.py run web
执行结果:
['test.py','run','web']
这个意思就是有的脚本后边可以跟参数,如果跟run我们就执行run,如果跟web 我们就执行web
2.sys.exit(n)退出程序,正常退出
3.sys.version 获取当前解释器的版本
4.sys.maxint 最大的Int值
5.sys.path 返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
6.sys.platform 返回操作平台的名称
7.sys.getrecursionlimit()获取递归的最大层数
8.sys.setrecursionlimit(1200) 设置最大递归层数
9.sys.getdefaultencoding() 获取解释器默认编码
10.sys.getfilesystemencoding 获取内存数据存到文件里的默认编码
shutil模块
高级的文件,文件夹,压缩包处理模块
shelve模块
json和pickle只能dump,load一次,假如我确实有好几种数据需要序列化,如果只能dump一次的话,这就意味着我自己要dump好几个文件,这个时候就感觉很low,难道没有办法允许我dump好几次吗?
shelve他是对pickle的封装,允许你dump多次,load多次,并且不会顺序乱,因为他是一种key-value的形式;(这个下去自己研究,这里不在多说了,因为它主要是对pickle封装的)shutil.copyfileobj(fsrc,fdst[,llength])将文件内容拷贝到另一个文件中,可以部分内容。
hashlib模块
Hash,一般翻译做“散列”,也有直接音译为”哈希”的,就是把任意长度的输入(又叫做预映射,pre-image),通过散列算法,变换成固定长度的输出,该输出就是散列值。这种转换是一种压缩映射,也就是,散列值的空间通常远小于输入的空间,不同的输入可能会散列成相同的输出,而不可能从散列值来唯一的确定输入值。简单的说就是一种将任意长度的消息压缩到某一固定长度的消息摘要的函数。HASH主要用于信息安全领域中加密算法,他把一些不同长度的信息转化成杂乱的128位的编码里,叫做HASH值.也可以说,hash就是找到一种数据内容和数据存放地址之间的映射关系。
MD5
输入任意长度的信息,经过处理,输出为128位的信息(数字指纹);不同的输入得到的不同的结果(唯一性);MD5算法的特点
1.压缩性:任意长度的数据,算出的MD5值的长度都是固定的
2.容易计算:从原数据计算出MD5值很容易
3.抗修改性:对原数据进行任何改动,修改一个字节生成的MD5值区别也会很大
4.强抗碰撞:已知原数据和MD5,想找到一个具有相同MD5值的数据(即伪造数据)是非常困难的。
The above is the detailed content of Related introduction to python modules. For more information, please follow other related articles on the PHP Chinese website!