一、time&datetime模块
常用选项如下:
import time
print(time.asctime()) #返回时间格式
print(time.localtime())#返回本地时间struct时间对象
#print(time.gmtime(time.time()-80000))
t1_str = time.strptime("2016/11/13","%Y/%m/%d")
print(t1_str) #将字符串转化成struct时间对象
print(time.strptime('2016-08-20 15:31:25',"%Y-%m-%d %H:%M:%S"))#同上
t2 = time.mktime(t1_str) #struct时间对象转化成时间戳
print(t2)
t3 = time.gmtime(time.time()) #将时间戳转化struct时间格式
print(t3)
print(time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()))
t4 = time.strftime("%Y-%m-%d %H-%M-%S",t3)
print(t4)
转换格式如下:
二、random模块
random随机数模块,用于生成随机数字
生成随机状态码方法:
1 import random 2 import string 3 print(random.random()) 4 print(random.randint(1,5)) 5 print(random.randrange(1,3)) 6 ---------第一种方法---------------------------------- 7 str_source = string.ascii_letters + string.digits 8 print(random.sample(str_source,7)) 9 ----------------第二种方法---------------------- 10 check = "" 11 for i in range(5): 12 current = random.randrange(0,5) 13 if current !=i: 14 temp = chr(random.randint(65,90)) 15 else: 16 temp = random.randint(0,9) 17 check+=str(temp) 18 print(check)
三、shutil模块
高级的文件压缩包处理模块
1 import shutil 2 shutil.copyfile("s1.py","s4.py")#copy文件 3 shutil.copy("s1.py","s4.py")#copy文件和权限 4 shutil.copy2("s1.py","s4.py")#copy文件和状态信息 5 shutil.copymode("s1.py","s4.py")#仅copy权限 6 shutil.rmtree(r"C:\Users\Administrator\PycharmProjects\s15\day1\a") #递归的删除文件 7 shutil.move(r"C:\Users\Administrator\PycharmProjects\s15\day1\lock",".") #移动文件 8 ret = shutil.make_archive("test",'gztar',root_dir=r"C:\Users\Administrator\PycharmProjects\s15\day1") 9 #test目标文件名,gztar 压缩类型,root_dir要压缩的文件路径
四、shelve模块
shelve模块是一个简单的k,v将内存数据通过文件持久化的模块,可以持久化任何pickle可支持的python数据格式
import shelve
d = shelve.open('shelve_test') #打开一个文件
class Test(object):
def __init__(self,n):
self.n = n
t = Test(123)
t2 = Test(123334)
name = ["alex","rain","test"]
d["test"] = name #持久化列表
d["t1"] = t #持久化类
d["t2"] = t2
d.close()
五、xml模块
xml是实现不同语言或程序之间进行数据交换的协议,跟json差不多,但json使用起来更简单。
xml格式如下,就是通过<>节点来区别数据结构:
1 <?xml version="1.0"?> 2 <data> 3 <country name="Liechtenstein"> 4 <rank updated="yes">2</rank> 5 <year>2008</year> 6 <gdppc>141100</gdppc> 7 <neighbor name="Austria" direction="E"/> 8 <neighbor name="Switzerland" direction="W"/> 9 </country> 10 <country name="Singapore"> 11 <rank updated="yes">5</rank> 12 <year>2011</year> 13 <gdppc>59900</gdppc> 14 <neighbor name="Malaysia" direction="N"/> 15 </country> 16 <country name="Panama"> 17 <rank updated="yes">69</rank> 18 <year>2011</year> 19 <gdppc>13600</gdppc> 20 <neighbor name="Costa Rica" direction="W"/> 21 <neighbor name="Colombia" direction="E"/> 22 </country> 23 </data>
xml协议在各个语言都是支持的,在python中可用使用以下模块操作:
1 import xml.etree.ElementTree as ET 2 3 tree = ET.parse("xmltest.xml") 4 root = tree.getroot() 5 print(root.tag) 6 7 #遍历xml文档 8 for child in root: 9 print(child.tag, child.attrib) 10 for i in child: 11 print(i.tag,i.text) 12 13 #只遍历year 节点 14 for node in root.iter('year'): 15 print(node.tag,node.text) 16 修改和删除xml文档内容 17 18 import xml.etree.ElementTree as ET 19 20 tree = ET.parse("xmltest.xml") 21 root = tree.getroot() 22 23 #修改 24 for node in root.iter('year'): 25 new_year = int(node.text) + 1 26 node.text = str(new_year) 27 node.set("updated","yes") 28 29 tree.write("xmltest.xml") 30 31 32 #删除node 33 for country in root.findall('country'): 34 rank = int(country.find('rank').text) 35 if rank > 50: 36 root.remove(country) 37 38 tree.write('output.xml') 39 自己创建xml文档 40 41 import xml.etree.ElementTree as ET 42 43 44 new_xml = ET.Element("namelist") 45 name = ET.SubElement(new_xml,"name",attrib={"enrolled":"yes"}) 46 age = ET.SubElement(name,"age",attrib={"checked":"no"}) 47 sex = ET.SubElement(name,"sex") 48 sex.text = '33' 49 name2 = ET.SubElement(new_xml,"name",attrib={"enrolled":"no"}) 50 age = ET.SubElement(name2,"age") 51 age.text = '19' 52 53 et = ET.ElementTree(new_xml) #生成文档对象 54 et.write("test.xml", encoding="utf-8",xml_declaration=True) 55 56 ET.dump(new_xml) #打印生成的格式
六、ConfigParser模块
用于生产和修改常见配置文档,举例如下:
1 [DEFAULT] 2 ServerAliveInterval = 45 3 Compression = yes 4 CompressionLevel = 9 5 ForwardX11 = yes 6 7 [bitbucket.org] 8 User = hg 9 10 [topsecret.server.com] 11 Port = 50022 12 ForwardX11 = no 13 如果想用python生成一个这样的文档怎么做呢? 14 15 import configparser 16 17 config = configparser.ConfigParser() 18 config["DEFAULT"] = {'ServerAliveInterval': '45', 19 'Compression': 'yes', 20 'CompressionLevel': '9'} 21 22 config['bitbucket.org'] = {} 23 config['bitbucket.org']['User'] = 'hg' 24 config['topsecret.server.com'] = {} 25 topsecret = config['topsecret.server.com'] 26 topsecret['Host Port'] = '50022' # mutates the parser 27 topsecret['ForwardX11'] = 'no' # same here 28 config['DEFAULT']['ForwardX11'] = 'yes' 29 with open('example.ini', 'w') as configfile: 30 config.write(configfile) 31 32 33 写完了还可以再读出来哈。 34 35 >>> import configparser 36 >>> config = configparser.ConfigParser() 37 >>> config.sections() 38 [] 39 >>> config.read('example.ini') 40 ['example.ini'] 41 >>> config.sections() 42 ['bitbucket.org', 'topsecret.server.com'] 43 >>> 'bitbucket.org' in config 44 True 45 >>> 'bytebong.com' in config 46 False 47 >>> config['bitbucket.org']['User'] 48 'hg' 49 >>> config['DEFAULT']['Compression'] 50 'yes' 51 >>> topsecret = config['topsecret.server.com'] 52 >>> topsecret['ForwardX11'] 53 'no' 54 >>> topsecret['Port'] 55 '50022' 56 >>> for key in config['bitbucket.org']: print(key) 57 ... 58 user 59 compressionlevel 60 serveraliveinterval 61 compression 62 forwardx11 63 >>> config['bitbucket.org']['ForwardX11'] 64 'yes' 65 configparser增删改查语法 66 67 [section1] 68 k1 = v1 69 k2:v2 70 71 [section2] 72 k1 = v1 73 74 import ConfigParser 75 76 config = ConfigParser.ConfigParser() 77 config.read('i.cfg') 78 79 # ########## 读 ########## 80 #secs = config.sections() 81 #print secs 82 #options = config.options('group2') 83 #print options 84 85 #item_list = config.items('group2') 86 #print item_list 87 88 #val = config.get('group1','key') 89 #val = config.getint('group1','key') 90 91 # ########## 改写 ########## 92 #sec = config.remove_section('group1') 93 #config.write(open('i.cfg', "w")) 94 95 #sec = config.has_section('wupeiqi') 96 #sec = config.add_section('wupeiqi') 97 #config.write(open('i.cfg', "w")) 98 99 100 #config.set('group2','k1',11111) 101 #config.write(open('i.cfg', "w")) 102 103 #config.remove_option('group2','age') 104 #config.write(open('i.cfg', "w"))
七、hashlib模块
用于加密相关的操作,用法如下:
1 import hashlib 2 m = hashlib.md5() 3 m.update(b"Hello") 4 m.update(b"It's me") 5 print(m.digest()) 6 m.update(b"") 7 print(m.digest()) #2进制格式hash 8 print(len(m.hexdigest())) #16进制 9 import hashlib 10 hash = hashlib.md5() 11 hash.update('admin') 12 print(hash.hexdigest()) 13 14 hash = hashlib.sha256() 15 hash.update('admin') 16 print(hash.hexdigest()) 17 18 hash = hashlib.sha512() 19 hash.update('admin') 20 print(hash.hexdigest()) 21 python 还有一个 hmac 模块,它内部对我们创建 key 和 内容 再进行处理然后再加密 22 23 import hmac 24 h = hmac.new('wueiqi') 25 h.update('hellowo') 26 print h.hexdigest()
八、日志模块
python的logging模块提供了标准的日志接口,你可以通过它存储各种格式的日志,logging的日志可以分为 debug()
, info()
, warning()
, error()
and critical() 5个级别,具体用法举例如下:
1 import logging 2 logging.basicConfig(filename='log.log',level=logging.INFO,format='%(asctime)s %(message)s',datefmt='%m/%d/%Y %I:%M:%S %p') 3 #logging.basicConfig(format='%(asctime)s %(message)s',datefmt='%m/%d/%Y %I:%M:%S %p') 4 logging.debug("debug") 5 logging.info("info") 6 logging.warning("warning") 7 logging.error("error") 8 logging.critical("critical") 9 logging.log(10,"log")
日志格式
%(name)s | Logger的名字 |
%(levelno)s | 数字形式的日志级别 |
%(levelname)s | 文本形式的日志级别 |
%(pathname)s | 调用日志输出函数的模块的完整路径名,可能没有 |
%(filename)s | 调用日志输出函数的模块的文件名 |
%(module)s | 调用日志输出函数的模块名 |
%(funcName)s | 调用日志输出函数的函数名 |
%(lineno)d | 调用日志输出函数的语句所在的代码行 |
%(created)f | 当前时间,用UNIX标准的表示时间的浮 点数表示 |
%(relativeCreated)d | 输出日志信息时的,自Logger创建以 来的毫秒数 |
%(asctime)s | 字符串形式的当前时间。默认格式是 “2003-07-08 16:49:45,896”。逗号后面的是毫秒 |
%(thread)d | 线程ID。可能没有 |
%(threadName)s | 线程名。可能没有 |
%(process)d | 进程ID。可能没有 |
%(message)s | 用户输出的消息 |
如果需要将log打印在屏幕里,需要用到handler,Python使用logging模块记录日志主要涉及四个主要类:
logger提供了应用程序可以直接使用的接口;
handler将(logger创建的)日志记录发送到合适的目的输出;
filter提供了细度设备来决定输出哪条日志记录;
formatter决定日志记录的最终输出格式。
九、re模块
常用正则表达式符号
'.' 默认匹配除\n之外的任意一个字符,若指定flag DOTALL,则匹配任意字符,包括换行
'^' 匹配字符开头,若指定flags MULTILINE,这种也可以匹配上(r"^a","\nabc\neee",flags=re.MULTILINE)
'$' 匹配字符结尾,或e.search("foo$","bfoo\nsdfsf",flags=re.MULTILINE).group()也可以
'*' 匹配*号前的字符0次或多次,re.findall("ab*","cabb3abcbbac") 结果为['abb', 'ab', 'a']
'+' 匹配前一个字符1次或多次,re.findall("ab+","ab+cd+abb+bba") 结果['ab', 'abb']
'?' 匹配前一个字符1次或0次
'{m}' 匹配前一个字符m次
'{n,m}' 匹配前一个字符n到m次,re.findall("ab{1,3}","abb abc abbcbbb") 结果'abb', 'ab', 'abb']
'|' 匹配|左或|右的字符,re.search("abc|ABC","ABCBabcCD").group() 结果'ABC'
'(...)' 分组匹配,re.search("(abc){2}a(123|456)c", "abcabca456c").group() 结果 abcabca456c
'\A' 只从字符开头匹配,re.search("\Aabc","alexabc") 是匹配不到的
'\Z' 匹配字符结尾,同$
'\d' 匹配数字0-9
'\D' 匹配非数字
'\w' 匹配[A-Za-z0-9]
'\W' 匹配非[A-Za-z0-9]
's' 匹配空白字符、\t、\n、\r , re.search("\s+","ab\tc1\n3").group() 结果 '\t'
'(?P<name>...)' 分组匹配 re.search("(?P<province>[0-9]{4})(?P<city>[0-9]{2})(?P<birthday>[0-9]{4})","371481199306143242").groupdict("city") 结果{'province': '3714', 'city': '81', 'birthday': '1993'}
最常用的匹配语法
re.match 从头开始匹配
re.search 匹配包含
re.findall 把所有匹配到的字符放到以列表中的元素返回
re.splitall 以匹配到的字符当做列表分隔符
re.sub 匹配字符并替换
关于反斜杠问题:
与大多数编程语言相同,正则表达式里使用"\"作为转义字符,这就可能造成反斜杠困扰。假如你需要匹配文本中的字符"\",那么使用编程语言表示的正则表达式里将需要4个反斜杠"\\\\":前两个和后两个分别用于在编程语言里转义成反斜杠,转换成两个反斜杠后再在正则表达式里转义成一个反斜杠。Python里的原生字符串很好地解决了这个问题,这个例子中的正则表达式可以使用r"\\"表示。同样,匹配一个数字的"\\d"可以写成r"\d"。有了原生字符串,你再也不用担心是不是漏写了反斜杠,写出来的表达式也更直观。