python中常用的库

python中的常用库

time库

1.python中表示时间的方式:
(1)时间戳
(2)格式化的时间字符串
(3)元组(struct_time)
包含如下九个元素

索引(Index) 属性(Attribute) 值(Values)
0 tm_year(年) 比如2019
1 tm_mon(月) 1 - 12
2 tm_mday(日) 1 - 31
3 tm_hour(时) 0 - 23
4 tm_min(分) 0 - 59
5 tm_sec(秒) 0 - 61
6 tm_wday(weekday) 0 - 6(0表示周日)
7 tm_yday(一年中的第几天) 1 - 366
8 tm_isdst(是否是夏令时) 默认为-1

由于Python的time模块实现主要调用C库,所以各个平台可能有所不同。
2.UTC(Coordinated Universal Time,世界协调时)亦即格林威治天文时间,世界标准时间。在中国为UTC+8。DST(Daylight Saving Time)即夏令时。
3.时间戳(timestamp)的方式:通常来说,时间戳表示的是从1970年1月1日00:00:00开始按秒计算的偏移量。
我们运行“type(time.time())”,返回的是float类型。返回时间戳方式的函数主要有time(),clock()等。
4.元组(struct_time)方式:struct_time元组共有9个元素,返回struct_time的函数主要有gmtime(),localtime(),strptime()。下面列出这种方式元组中的几个元素:

import time
#time.localtime([secs]):将一个时间戳转换为当前时区的struct_time。secs参数未提供,则以当前时间为准。
In [2]: time.localtime()
Out[2]: time.struct_time(tm_year=2019, tm_mon=11, tm_mday=21, tm_hour=19, tm_min=2, tm_sec=45, tm_wday=3, tm_yday=325, tm_isdst=0)


#time.gmtime([secs]):和localtime()方法类似,gmtime()方法是将一个时间戳转换为UTC时区(0时区)的struct_time。
In [4]: time.gmtime()
Out[4]: time.struct_time(tm_year=2019, tm_mon=11, tm_mday=21, tm_hour=11, tm_min=32, tm_sec=3, tm_wday=3, tm_yday=325, tm_isdst=0)



#time.time():返回当前时间的时间戳。
In [3]: time.time()
Out[3]: 1574334179.0769079


#time.mktime(t):将一个struct_time转化为时间戳。
In [7]: time.mktime(time.localtime())
Out[7]: 1574335985.0


#time.sleep(secs):线程推迟指定的时间运行。单位为秒。


#time.clock():这个需要注意,在不同的系统上含义不同。在UNIX系统上,它返回的是“进程时间”,它是用秒表示的浮点数(时间戳)。
#而在WINDOWS中,第一次调用,返回的是进程运行的实际时间。而第二次之后的调用是自第一次调用以后到现在的运行时间。
#实际上是以WIN32上QueryPerformanceCounter()为基础,它比毫秒表示更为精确)

if __name__ == '__main__':  
    time.sleep(1)  
    print "clock1:%s" % time.clock()  
    time.sleep(1)  
    print "clock2:%s" % time.clock()  
    time.sleep(1)  
    print "clock3:%s" % time.clock()

#输出:
clock1:3.35238137808e-006 
clock2:1.00004944763 
clock3:2.00012040636
其中第一个clock()输出的是程序运行时间
第二、三个clock()输出的都是与第一个clock的时间间隔



#time.asctime([t]):把一个表示时间的元组或者struct_time表示为这种形式:'Sun Jun 20 23:21:05 2019'。
#如果没有参数,将会将time.localtime()作为参数传入。

In [14]: time.asctime()
Out[14]: 'Thu Nov 21 19:35:32 2019'

#time.ctime([secs]):把一个时间戳(按秒计算的浮点数)转化为time.asctime()的形式。
#如果参数未给或者为None的时候,将会默认time.time()为参数。
#它的作用相当于time.asctime(time.localtime(secs))。
In [15]: time.ctime()
Out[15]: 'Thu Nov 21 19:36:05 2019'

In [16]: time.ctime(time.time())
Out[16]: 'Thu Nov 21 19:36:11 2019'

In [17]: time.ctime(788489489)
Out[17]: 'Tue Dec 27 08:51:29 1994'



#time.strftime(format[, t]):把一个代表时间的元组或者struct_time
#(如由time.localtime()和time.gmtime()返回)转化为格式化的时间字符串。
#如果t未指定,将传入time.localtime()。
#如果元组中任何一个元素越界,ValueError的错误将会被抛出。
'''
格式				含义																			
%a				本地(locale)简化星期名称	
%A				本地完整星期名称	
%b				本地简化月份名称	
%B				本地完整月份名称	
%c				本地相应的日期和时间表示	
%d				一个月中的第几天(01 - 31)	
%H				一天中的第几个小时(24小时制,00 - 23)	
%I				第几个小时(12小时制,01 - 12)	
%j				一年中的第几天(001 - 366)	
%m				月份(01 - 12)	
%M				分钟数(00 - 59)	
%p				本地am或者pm的相应符	
%S				秒(01 - 61)	
%U				一年中的星期数。(00 - 53星期天是一个星期的开始。)第一个星期天之前的所有天数都放在第0周。	
%w				一个星期中的第几天(0 - 6,0是星期天)													
%W				和%U基本相同,不同的是%W以星期一为一个星期的开始。	
%x				本地相应日期	
%X				本地相应时间	
%y				去掉世纪的年份(00 - 99)	
%Y				完整的年份	
%Z				时区的名字(如果不存在为空字符)	
%%				'%'字符


备注:
“%p”只有与“%I”配合使用才有效果。
官方文档中强调确实是0-61,而不是59,闰年秒占两秒。。。。
当使用strptime()函数时,只有当在这年中的周数和天数被确定的时候%U和%W才会被计算。

'''

In [18]: time.strftime("%Y-%m-%d %X", time.localtime())
Out[18]: '2019-11-21 19:37:01'


#time.strptime(string[, format]):把一个格式化时间字符串转化为struct_time。
#实际上它和strftime()是逆操作。
In [23]:  time.strptime('2019-11-21 20:51:06', '%Y-%m-%d %X')
Out[23]: time.struct_time(tm_year=2019, tm_mon=11, tm_mday=21, tm_hour=20, tm_min=51, tm_sec=6, tm_wday=3, tm_yday=325, tm_isdst=-1)

#在这个函数中,format默认为:"%a %b %d %H:%M:%S %Y"。

os库

1.用来提供系统级别的操作

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


>>> os.path.join('c:\\', 'txt', 'test.txt') 
'c:\\txt\\test.txt' 
>>> os.path.join('windows\temp', 'c:\\', 'csv', 'test.csv') 
'c:\\csv\\test.csv' 
>>> os.path.join('/home/aa','/home/aa/bb','/home/aa/bb/c') 
'/home/aa/bb/c'

random库

import random
print (random.random())  #random.random()用于生成一个0到1的随机符点数
print (random.randint(1,7)) #随机生成一个指定范围内的整数
print (random.randrange(1,10)) #random.randrange的函数原型为:random.randrange([start], stop[, step]),
# 从指定范围内,按指定步长的集合中 获取一个随机数。如:random.randrange(1, 10, 2),
# 结果相当于从[1,3, 5, 9]序列中获取一个随机数。
# random.randrange(1, 10, 2)在结果上与 random.choice(range(1, 10, 2) 一样。
print(random.choice('lcaasdad')) #l
#random.choice从序列中获取一个随机元素。
# 其函数原型为:random.choice(sequence)。参数sequence表示一个有序类型。
# 这里要说明一下:sequence在python不是一种特定的类型,而是泛指一系列的类型。
# list, tuple, 字符串都属于sequence。
# 下面是使用choice的一些例子:
print(random.choice("你好world"))#你
print(random.choice(["hh","da","sadad","mmck","boy"]))  #List
print(random.choice(("Tuple","List","Dict")))   #List
print(random.sample([1,2,3,4,5],3))    #[1, 2, 5]
#random.sample的函数原型为:random.sample(sequence, k),从指定序列中随机获取指定长度的片断。sample函数不会修改原有序列。


#几个实际运用的小例子
import random
import string
#随机整数:
print( random.randint(0,50))

#随机选取0到50间的偶数:
print(random.randrange(0, 51, 2)) 

#随机浮点数:
print( random.random()) 
print(random.uniform(1, 5)) 

#随机字符:
print(random.choice('hadsad!@##das')) 

#多个字符中选取特定数量的字符:
print(random.sample('abcdefghij',3)) #['f', 'h', 'd']

#随机选取字符串:
print( random.choice ( ['apple', 'pear', 'peach', 'orange', 'lemon'] )) #apple
#洗牌#
items = [1,2,3,4,5,6,7]
print(items) #[1, 2, 3, 4, 5, 6, 7]
random.shuffle(items)
print(items) #[1, 4, 7, 2, 5, 3, 6]




#使用此模块生成一个简单的随机验证码
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)

sys库

sys.argv           #命令行参数List,第一个元素是程序本身路径
sys.exit(n)        #退出程序,正常退出时exit(0)
sys.version        #获取Python解释程序的版本信息
sys.maxint         #最大的Int值
sys.path           #返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
sys.platform       #返回操作系统平台名称
sys.stdout.write('please:')   #标准化输出
val = sys.stdin.readline()[:-1]  #标准化输入

shutil库

参考http://www.cnblogs.com/wupeiqi/articles/4963027.html

shelve库

1.shelve库是一个简单的将k,v内存数据进行文件持久化的模块,它可以持久化任何pickle可支持的python数据格式。

'''
#实例1:
import shelve
 
d = shelve.open('shelve_test') #打开一个文件 
 
class Test(object):
    def __init__(self,n):
        self.n = n
 
 
t = Test(123)  
t2 = Test(123334)
 
name = ["cay","rain","test"] 
d["test"] = name #持久化列表
d["t1"] = t      #持久化类
d["t2"] = t2
 
d.close()
'''




'''
#实例2:
import shelve
import datetime

info =  {'age':22,"job":'it'}
name = ["alex", "rain", "test"]
d["name"] = name  # 持久化列表
d["info"] = info  # 持久dict
d['date'] = datetime.datetime.now()
d.close()
d = shelve.open('shelve_test')  # 打开一个文件

#使用读取字典的方式读取所持久化的数据
print(d.get("name")) 
print(d.get("info"))
print(d.get("date"))
'''



Hashlib、Hmac库

1.用于加密相关的操作,代替了md5模块和sha模块,主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 算法(按照算法的复杂程度)

import hashlib
 
# ######## md5 ########
 
hash = hashlib.md5()   #使用MD5加密方法进行加密
hash.update(b'cay')   #要使用bytes类型的字符串才能加密,否则会报错TypeError: Unicode-objects must be encoded before hashing
hash.update('cay'.encode('utf-8'))   #这种方式也可以将字符串解码为bytes类型,在python3中
print (hash.hexdigest())  #打印加密后的MD5值
 
# ######## sha1 ########
 
hash = hashlib.sha1()  #使用sha1算法进行加密
hash.update(b'cay')  
print( hash.hexdigest())
 
# ######## sha256 ########
 
hash = hashlib.sha256() #使用sha256算法进行加密
hash.update('cay')
print (hash.hexdigest())
 
 
# ######## sha384 ########
 
hash = hashlib.sha384()
hash.update('cay')
print (hash.hexdigest())
 
# ######## sha512 ########
 
hash = hashlib.sha512()
hash.update('cay')
print( hash.hexdigest())

#以上为普通加密,有时候通过撞库可以反解出原密码
#所以,有必要对加密算法中添加自定义key再来做加密。

import hashlib
 
# ######## md5 ########
 
hash = hashlib.md5(b'asdadaa')
hash.update(b'cay')
hash.hexdigest()
#自定义key后的MD5值'77db7928b53e4bde1c28c45c6691eac7'

hash = hashlib.md5()
hash.update(b'cay')
hash.hexdigest()
#不定义key时得到的值'285d7b6cf94d8fdc657edaa73c2f07f3'
#要想再提高安全系数,python 还有一个 hmac 模块,它内部对我们创建key和内容再进行处理然后再加密


import hmac
h = hmac.new('hello')
h.update('cay')
print( h.hexdigest())

#我能了解到的加密就到这了。。。

re库

1.编写正则表达式时所要使用到的库

ConfigParse库

用于生成和修改常见配置文档

#一个软件的常见文档格式
[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes
 
[bitbucket.org]
User = hg
 
[topsecret.server.com]
Port = 50022
ForwardX11 = no

#使用ConfigParser来生成这样一个配置文件
import configparser
 
config = configparser.ConfigParser()
config["DEFAULT"] = {'ServerAliveInterval': '45',
                      'Compression': 'yes',
                     'CompressionLevel': '9'}
 
config['bitbucket.org'] = {}
config['bitbucket.org']['User'] = 'hg'
config['topsecret.server.com'] = {}
topsecret = config['topsecret.server.com']
topsecret['Host Port'] = '50022'     # mutates the parser
topsecret['ForwardX11'] = 'no'  # same here
config['DEFAULT']['ForwardX11'] = 'yes'
with open('example.ini', 'w') as configfile:
   config.write(configfile)


#生成配置文件之后再将其读出
>>> import configparser
>>> config = configparser.ConfigParser()
>>> config.sections()
[]
>>> config.read('example.ini')
['example.ini']
>>> config.sections()
['bitbucket.org', 'topsecret.server.com']
#为什么default没有打印出来呢?
#默认不打印
>>>print(config.defaults())
#把所有的key显式的打印出来,包括default
>>> 'bitbucket.org' in config
True
>>> 'bytebong.com' in config
False
>>> config['bitbucket.org']['User']
'hg'
>>> config['DEFAULT']['Compression']
'yes'
>>> topsecret = config['topsecret.server.com']
>>> topsecret['ForwardX11']
'no'
>>> topsecret['Port']
'50022'
>>> for key in config['bitbucket.org']: print(key)
...
user
compressionlevel
serveraliveinterval
compression
forwardx11
>>> config['bitbucket.org']['ForwardX11']
'yes'


#增删改查配置文件
[section1]
k1 = v1
k2:v2
  
[section2]
k1 = v1
 
import ConfigParser
  
config = ConfigParser.ConfigParser()
config.read('i.cfg')
  
# ########## 读 ##########
#secs = config.sections()
#print secs
#options = config.options('group2')
#print options
  
#item_list = config.items('group2')
#print item_list
  
#val = config.get('group1','key')
#val = config.getint('group1','key')
  
# ########## 改写 ##########
#sec = config.remove_section('group1')
#config.write(open('i.cfg', "w"))
  
#sec = config.has_section('wupeiqi')
#sec = config.add_section('wupeiqi')
#config.write(open('i.cfg', "w"))
  
  
#config.set('group2','k1',11111)
#config.write(open('i.cfg', "w"))
  
#config.remove_option('group2','age')
#config.write(open('i.cfg', "w"))
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值