python常用模块详解(一)

一.简介

  模块是一个保存了Python代码的文件。模块能定义函数,类和变量。模块里也能包含可执行的代码

  模块分为三种:

  • 自定义模块
  • 内置标准模块
  • 开源模块(第三方)

自定义模块:

  

模块导入

import module
from module.xx.xx import xx
from module.xx.xx import xx as rename  
from module.xx.xx import *

导入自定义模块时注意路径,查看库文件sys.path,sys.path.append('路径')添加自定义路径

二.内置模块

time模块

time模块提供各种操作时间的函数

说明:一般有两种表示时间的方式:
       1.时间戳的方式(相对于1970.1.1 00:00:00以秒计算的偏移量),时间戳是惟一的
       2.以数组的形式表示即(struct_time),共有九个元素,分别表示,同一个时间戳的struct_time会因为时区不同而不同


The tuple items are:
year (including century, e.g. 1998)
month (1-12)
day (1-31)
hours (0-23)
minutes (0-59)
seconds (0-59)
weekday (0-6, Monday is 0)
Julian day (day in the year, 1-366)
DST (Daylight Savings Time) flag (-1, 0 or 1)
 
  •  函数
time() -- 返回时间戳
sleep() -- 延迟运行单位为s
gmtime() -- 转换时间戳为时间元组(时间对象)
localtime() -- 转换时间戳为本地时间对象
asctime() -- 将时间对象转换为字符串
ctime() -- 将时间戳转换为字符串
mktime() -- 将本地时间转换为时间戳
strftime() -- 将时间对象转换为规范性字符串

常用的格式代码:

%Y Year with century as a decimal number.
%m Month as a decimal number [01,12].
%d Day of the month as a decimal number [01,31].
%H Hour (24-hour clock) as a decimal number [00,23].
%M Minute as a decimal number [00,59].
%S Second as a decimal number [00,61].
%z Time zone offset from UTC.
%a Locale's abbreviated weekday name.
%A Locale's full weekday name.
%b Locale's abbreviated month name.
%B Locale's full month name.
%c Locale's appropriate date and time representation.
%I Hour (12-hour clock) as a decimal number [01,12].
%p Locale's equivalent of either AM or PM.


strptime() -- 将时间字符串根据指定的格式化符转换成数组形式的时间
常用格式代码:
strftime
  • 举例
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import time


#返回当前时间戳
print(time.time())
#返回当前时间
print(time.ctime())
#将时间戳转换为字符串
print(time.ctime(time.time()-86640))
#本地时间
print(time.localtime(time.time()-86400))
#与time.localtime()功能相反,将struct_time格式转回成时间戳格式
print(time.mktime(time.localtime()))
#将struct_time格式转成指定的字符串格式
print(time.strftime("%Y-%m-%d %H:%M:%S",time.gmtime()))
#将字符串格式转换成struct_time格式
print(time.strptime("2016-01-28","%Y-%m-%d"))
#休眠5s
time.sleep(5)
View Code

2.datetime模块

定义的类有: 
datetime.date    --表示日期的类。常用的属性有year, month, day
datetime.time    --表示时间的类。常用的属性有hour, minute, second, microsecond

datetime.datetime  --表示日期时间
datetime.timedelta   --表示时间间隔,即两个时间点之间的长度

  • date类

date类表示日期,构造函数如下 :

datetime.date(year, month, day);

year (1-9999)

month (1-12)

day (1-31)

date.today()  --返回一个表示当前本地日期的date对象

date.fromtimestamp(timestamp) --根据给定的时间戮,返回一个date对象

 

#根据给定的时间戮,返回一个date对象
print(datetime.date.fromtimestamp(time.time()))
#返回一个表示当前本地日期的date对象
print(datetime.datetime.today())
View Code

 

    date.year()   --取给定时间的年

    date.month()  --取时间对象的月

    date.day()  --取给定时间的日

date.replace()  --生成一个新的日期对象,用参数指定的年,月,日代替原有对象中的属性

date.timetuple()  --返回日期对应的time.struct_time对象

date.weekday()  --返回weekday,Monday == 0 ... Sunday == 6

date.isoweekday() --返回weekday,Monday == 1 ... Sunday == 7

date.ctime()    --返回给定时间的字符串格式

import datetime
from dateutil.relativedelta import relativedelta
# 获取当前时间的前一个月
datetime.datetime.now() - relativedelta(months=+1)
# 获取当天的前一个月
datetime.date.today() - relativedelta(months=+1) 
#取时间对象的年
print(datetime.date.today().year)
#取时间对象的月
print(datetime.date.today().month)
#取时间对象的日
print(datetime.date.today().day)
#生成一个新的日期对象,用参数指定的年,月,日代替原有对象中的属性
print(datetime.date.today().replace(2010,6,12))
#返回给定时间的时间元组/对象
print(datetime.date.today().timetuple())
#返回weekday,从0开始
print(datetime.date.today().weekday())
#返回weekday,从1开始
print(datetime.date.today().isoweekday())
#返回给定时间的字符串格式
print(datetime.date.today().ctime())
View Code
  • time 类

time类表示时间,由时、分、秒以及微秒组成

time.min()  --最小表示时间

time.max()  --最大表示时间

time.resolution()  --微秒

 

#最大时间
print(datetime.time.max)
#最小时间
print(datetime.time.min)
#时间最小单位,微秒
print(datetime.time.resolution)
View Code

 

  • datetime类

datetime是date与time的结合体,包括date与time的所有信息

datetime.max()  --最大值

datetime.min()  --最小值

datetime.resolution() --datetime最小单位

datetime.today()  --返回一个表示当前本地时间

datetime.fromtimestamp()  --根据给定的时间戮,返回一个datetime对象

datetime.year()  --取年

datetime.month()  --取月

datetime.day()  --取日期

datetime.replace()  --替换时间

datetime.strptime()  --将字符串转换成日期格式

datetime.time()  --取给定日期时间的时间  

#datetime最大值
print(datetime.datetime.max)
#datetime最小值
print(datetime.datetime.min)
#datetime最小单位
print(datetime.datetime.resolution)
#返回一个表示当前本地时间
print(datetime.datetime.today())
#根据给定的时间戮,返回一个datetime对象
print(datetime.datetime.fromtimestamp(time.time()))
#取时间对象的年
print(datetime.datetime.now().year)
#取时间对象的月
print(datetime.datetime.now().month)
#取时间对象的日
print(datetime.datetime.now().day)
#生成一个新的日期对象,用参数指定的年,月,日代替原有对象中的属性
print(datetime.datetime.now().replace(2010,6,12))
#返回给定时间的时间元组/对象
print(datetime.datetime.now().timetuple())
#返回weekday,从0开始
print(datetime.datetime.now().weekday())
#返回weekday,从1开始
print(datetime.datetime.now().isoweekday())
#返回给定时间的字符串格式
print(datetime.datetime.now().ctime())
#将字符串转换成日期格式
print(datetime.datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M"))
#取给定日期时间的时间
print(datetime.datetime.now().time())
#获取5日前时间
print(datetime.datetime.now() + datetime.timedelta(days=-5))
View Code

3.sys模块

   用于提供对解释器相关的访问及维护,并有很强的交互功能

常用函数:

sys.argv --传参,第一个参数为脚本名称即argv[0]

sys.path --模块搜索路径

sys.moudule --加载模块字典

sys.stdin  --标准输入

sys.stdout  --标准输出

sys.stderr  --错误输出

sys.platform --返回系统平台名称

sys.version  --查看python版本

sys.maxsize  --最大的Int值

举例:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
#传参
import sys

print(sys.argv[0])
print(sys.argv[1])
print(sys.argv[2])


##运行
python argv.py argv0 argv1
argv.py
argv0
argv1
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import sys,os

dirname = sys.stdin.read()
os.mkdir(dirname.strip())
View Code
#sys.exit()系统返回值 

>>> import sys
>>> sys.exit(0)

C:>echo %ERRORLEVEL%
0

#windows查看系统返回值命令
echo %ERRORLEVEL%
#linux查看系统返回值命令
echo $?
>>> import sys
>>> sys.platform
'win32'
>>> sys.version
'3.5.1 (v3.5.1:37a07cee5969, Dec  6 2015, 01:54:25) [MSC v.1900 64 bit (AMD64)]'

>>> sys.maxsize
9223372036854775807
View Code
import sys,time
for i in range(100):
    sys.stdout.write('r')
    sys.stdout.write('%s%% |%s' % (int(i/100*100),int(i/100*100) * '*'))
    sys.stdout.flush
    time.sleep(0.2)
View Code

4.pickle模块

  pickle,用于python特有的类型 和 python的数据类型间进行转换

 pickle模块提供了四个功能:dumps、dump、loads、load

Functions:

dump(object, file)
dumps(object) -> string
load(file) -> object
loads(string) -> object

pickle.dumps(obj)--把任意对象序列化成一个str,然后,把这个str写入文件
pickle.loads(string)  --反序列化出对象
pickle.dump(obj,file)  --直接把对象序列化后写入文件
pickle.load(file)
  --从文件中反序列化出对象
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import pickle
accounts = {
    1000: {
        'name':'USERA',
        'email': 'lijie3721@126.com',
        'passwd': 'abc123',
        'balance': 15000,
        'phone': 13651054608,
        'bank_acc':{
            'ICBC':14324234,
            'CBC' : 235234,
            'ABC' : 35235423
        }
    },
    1001: {
        'name': 'USERB',
        'email': 'caixin@126.com',
        'passwd': 'abc145323',
        'balance': -15000,
        'phone': 1345635345,
        'bank_acc': {
            'ICBC': 4334343,
        }
    },
}
#把字典类型写入到文件中
f = open('accounts.db','wb')
f.write(pickle.dumps(accounts))
f.close()

#2,反序列出对象并修改其内容,并将修改内容重新写入文件
file_name = "accounts.db"
f = open(file_name,'rb')
account_dic = pickle.loads(f.read())
f.close()

account_dic[1000]['balance'] -= 500
f = open(file_name,'wb')
f.write(pickle.dumps(account_dic))
f.close()


#3,反序列化对象并查看其内容

f = open('accounts.db','rb')
acountdb = pickle.loads(f.read())
print(acountdb)
dic = {
    'k1': [1,2],
    'k2': [3,4]
}
#1.将对象写入文件
f = open('test','wb')
pickle.dump(dic,f)
f.close()
#2.将文件中内容反序列化,并读出
f = open('test','rb')
dic2 = pickle.load(f)
print(dic2)
f.close()

5.os模块

作用:

  用于提供系统级别的操作

函数: 

 1 os.getcwd()                 获取当前工作目录,即当前python脚本工作的目录路径
 2 os.chdir("dirname")         改变当前脚本工作目录;相当于shell下cd
 3 os.curdir                   返回当前目录: ('.')
 4 os.pardir                   获取当前目录的父目录字符串名:('..')
 5 os.makedirs('dir1/dir2')    可生成多层递归目录
 6 os.removedirs('dirname1')   若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推
 7 os.mkdir('dirname')         生成单级目录;相当于shell中mkdir dirname
 8 os.rmdir('dirname')         删除单级空目录,若目录不为空则无法删除,报错;相当于shell中rmdir dirname
 9 os.listdir('dirname')       列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印
10 os.remove()                 删除一个文件
11 os.rename("oldname","new")  重命名文件/目录
12 os.stat('path/filename')    获取文件/目录信息
13 os.sep                      操作系统特定的路径分隔符,win下为"\",Linux下为"/"
14 os.linesep                  当前平台使用的行终止符,win下为"	
",Linux下为"
"
15 os.pathsep                  用于分割文件路径的字符串
16 os.name                     字符串指示当前使用平台。win->'nt'; Linux->'posix'
17 os.system("bash command")   运行shell命令,直接显示
18 os.environ                  获取系统环境变量
19 os.path.abspath(path)       返回path规范化的绝对路径
20 os.path.split(path)         将path分割成目录和文件名二元组返回
21 os.path.dirname(path)       返回path的目录。其实就是os.path.split(path)的第一个元素
22 os.path.basename(path)      返回path最后的文件名。如何path以/或结尾,那么就会返回空值。即os.path.split(path)的第二个元素
23 os.path.exists(path)        如果path存在,返回True;如果path不存在,返回False
24 os.path.isabs(path)         如果path是绝对路径,返回True
25 os.path.isfile(path)        如果path是一个存在的文件,返回True。否则返回False
26 os.path.isdir(path)         如果path是一个存在的目录,则返回True。否则返回False
27 os.path.join(path1[, path2[, ...]])  将多个路径组合后返回,第一个绝对路径之前的参数将被忽略
28 os.path.getatime(path)      返回path所指向的文件或者目录的最后存取时间
29 os.path.getmtime(path)      返回path所指向的文件或者目录的最后修改时间

6.hashlib模块

  作用:

  用于加密相关的操作,代替了md5模块和sha模块,主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 算法 

import hashlib
 
# ######## md5 ########
hash = hashlib.md5()
# help(hash.update)
hash.update(bytes('admin', encoding='utf-8'))
print(hash.hexdigest())
print(hash.digest())
 
 
######## sha1 ########
 
hash = hashlib.sha1()
hash.update(bytes('admin', encoding='utf-8'))
print(hash.hexdigest())
 
# ######## sha256 ########
 
hash = hashlib.sha256()
hash.update(bytes('admin', encoding='utf-8'))
print(hash.hexdigest())
 
 
# ######## sha384 ########
 
hash = hashlib.sha384()
hash.update(bytes('admin', encoding='utf-8'))
print(hash.hexdigest())
 
# ######## sha512 ########
 
hash = hashlib.sha512()
hash.update(bytes('admin', encoding='utf-8'))
print(hash.hexdigest())
View Code

  加密算法缺陷,即:通过撞库可以反解。所以,有必要对加密算法中添加自定义key再来做加密

import hashlib
 
# ######## md5 ########
 
hash = hashlib.md5(bytes('898oaFs09f',encoding="utf-8"))
hash.update(bytes('admin',encoding="utf-8"))
print(hash.hexdigest())
View Code

  7.random

  作用:

  生成随机变量

import random
 
print(random.random())
print(random.randint(1, 2))
print(random.randrange(1, 10))
import random
checkcode = ''
for i in range(4):
    current = random.randrange(0,4)
    if current != i:
        temp = chr(random.randint(65,90))
    else:
        temp = random.randint(0,9)
    checkcode += str(temp)
print checkcode
原文地址:https://www.cnblogs.com/jl-bai/p/5505971.html