模块介绍
1.定义;模块:用来从逻辑上组织python代码(变量,函数,类,逻辑:实现一个功能),本质就是.py结尾的python文件;
包:用来从逻辑上组织模块,本质就是一个(目录)(必须带有一个_init_.py文件)
2.导入方法;import module_name
import module_1,module_2
from module_test import *(导入文件中的多个模块,不建议用)
from module_test import m1,m2,m3
from module_test import logger as logger_zhang
3.import本质(路径搜索和搜索路径);就是python文件整理一遍;
导入包,就是执行包下的(_init_.py文件);
import module_name------->module_name.py----------->module_name.py的路径;---》sys.path
(from test import name = 'code') ;
import sys,os
print(sys.path)
x=os.path.dirname(os.path.dirname(os.path.abspath(_file_)))
sys.path.append(x)
4.导入优化;
from module_test import test
5模块的的分类:
a:标准库(解释器自带);1time与datatime
strftime("格式",struct_time)
b:开源模块(第三方库);
c:自定义模块;
gmtime:结果为UTC时区;
localtime:结果为UT+8;
import time x=time.localtime() print(x) print(x.tm_year) print('this is 2018 day %s' %(x.tm_yday))
2:random模块;
import random checkcode='' for i in range(4): current = random.randint(1,9) checkcode+=str(current) print(checkcode)
加字母
import random checkcode='' for i in range(4): current = random.randrange(0,4) if current ==i: tmp=chr(random.randint(65,90)) else: tmp=random.randint(0,9) checkcode += str(tmp) print(checkcode)
3.os模块
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所指向的文件或者目录的最后修改时间
4.sys模块
2
3
4
5
6
7
8
|
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
]
|
5shutil 模块
直接参考 http://www.cnblogs.com/wupeiqi/articles/4963027.htmlshutil.copyfileobj(fsrc, fdst[, length])
def copyfileobj(fsrc, fdst, length=16*1024): """copy data from file-like object fsrc to file-like object fdst""" while 1: buf = fsrc.read(length) if not buf: break fdst.write(buf)
shutil.copyfile(src, dst)
def copyfile(src, dst): """Copy data from src to dst""" if _samefile(src, dst): raise Error("`%s` and `%s` are the same file" % (src, dst)) for fn in [src, dst]: try: st = os.stat(fn) except OSError: # File most likely does not exist pass else: # XXX What about other special files? (sockets, devices...) if stat.S_ISFIFO(st.st_mode): raise SpecialFileError("`%s` is a named pipe" % fn) with open(src, 'rb') as fsrc: with open(dst, 'wb') as fdst: copyfileobj(fsrc, fdst)
6.json&pickle模块
json,用于字符串和python数据类型进行转换
pickle,用于python特有类型和python的数据间进行装换;
7.shelve模块
shelve模块是一个简单的k,v将内存数据通过文件持久化的模块,可以持久化任何pickle可支持python数据格式;
import shelve import datetime d= shelve.open('shelve_test') info = {'age':23,"job":'it'} name= ["zhang","guo","qi"] d["name"] = name #持久化表 d["info"] = info#持久dict d['date'] = datetime.datetime.now() d.close()
读出来
import shelve import datetime d= shelve.open('shelve_test')#打开一个文件 print(d.get("name")) print(d.get("info")) print(d.get("date"))
结果
8.xml文件
<?
xml
version="1.0"?>
<
data
>
<
country
name="Liechtenstein">
<
rank
updated="yes">2</
rank
>
<
year
>2008</
year
>
<
gdppc
>141100</
gdppc
>
<
neighbor
name="Austria" direction="E"/>
<
neighbor
name="Switzerland" direction="W"/>
</
country
>
<
country
name="Singapore">
<
rank
updated="yes">5</
rank
>
<
year
>2011</
year
>
<
gdppc
>59900</
gdppc
>
<
neighbor
name="Malaysia" direction="N"/>
</
country
>
<
country
name="Panama">
<
rank
updated="yes">69</
rank
>
<
year
>2011</
year
>
<
gdppc
>13600</
gdppc
>
<
neighbor
name="Costa Rica" direction="W"/>
<
neighbor
name="Colombia" direction="E"/>
</
country
>
</
data
>
import
xml.etree.ElementTree as ET
tree
=
ET.parse(
"xmltest.xml"
)
root
=
tree.getroot()
print
(root.tag)
for
child
in
root:
print
(child.tag, child.attrib)
for
i
in
child:
print
(i.tag,i.text)
for
node
in
root.
iter
(
'year'
):
print
(node.tag,node.text)
import xml.etree.ElementTree as ET tree = ET.parse("xmltest.xml") root = tree.getroot() #修改 for node in root.iter('year'): new_year = int(node.text)+1 node.test = str(new_year) node.set("updateed_by","yes") tree.write("xmltest.xml") #删除 for country in root.findall('country'): rank = int(country.find('rank').text) if rank > 50: root.remove(country) tree.write('output.xml')
创建xml
import xml.etree.ElementTree as ET new_xml = ET.Element("namelist") name = ET.SubElement(new_xml, "name", attrib={"enrolled": "yes"}) age = ET.SubElement(name, "age", attrib={"checked": "no"}) sex = ET.SubElement(name, "sex") sex.text = '33' name2 = ET.SubElement(new_xml, "name", attrib={"enrolled": "no"}) age = ET.SubElement(name2, "age") age.text = '19' et = ET.ElementTree(new_xml) # 生成文档对象 et.write("test.xml", encoding="utf-8", xml_declaration=True) ET.dump(new_xml) # 打印生成的格式
创建2
import xml.etree.ElementTree as ET new_xml = ET.Element("personinfolist") personinfo = ET.SubElement(new_xml, "personinfo", attrib={"enrolled": "yes"}) name = ET.SubElement(personinfo, "name", attrib={"checked": "no"}) name.text = "zhang" sex = ET.SubElement(personinfo, "sex") sex.text = '33' personinfo2 = ET.SubElement(new_xml, "personinfo", attrib={"enrolled": "no"}) name = ET.SubElement(personinfo, "name", attrib={"checked": "no"}) name.text = "zhang" age = ET.SubElement(personinfo2, "age") age.text = '19' et = ET.ElementTree(new_xml) # 生成文档对象 et.write("test.xml", encoding="utf-8", xml_declaration=True) ET.dump(new_xml) # 打印生成的格式
结果
<?xml version='1.0' encoding='utf-8'?> <personinfolist> <personinfo enrolled="yes"> <name checked="no">zhang</name> <sex>33</sex> <name checked="no">zhang</name> </personinfo> <personinfo enrolled="no"> <age>19</age> </personinfo> </personinfolist>
9.PyYAML模块
10.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)
结果
[DEFAULT] ServerAliveInterval = 45 Compression = yes CompressionLevel = 9 ForwardX11 = yes [bitbucket.org] User = hg [topsecret.server.com] Port = 50022 ForwardX11 = no
读
import configparser conf = configparser.ConfigParser() conf.read("example.ini") print(conf.defaults()) print(conf['bitbucket.org']['user'])结果
删
sec = conf.remove_section('bitbucket.org')
11.hashlib模块
#!/usr/bin/env python import hashlib m = hashlib.md5() m.update(b"hello") print(m.hexdigest()) m.update(b"*****") print(m.hexdigest()) m.update(b"-------") print(m.hexdigest())
结果
import hashlib m = hashlib.md5() m.update(b"hello") print(m.hexdigest()) m.update(b"*****") print(m.hexdigest()) m.update(b"-------") print(m.hexdigest()) m2 = hashlib.md5() m2.update(b"HelloIt's me") print(m2.hexdigest()) s2 = hashlib.sha1() m2.update(b"HelloIt's me") print(s2.hexdigest())12. 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'
re.match 从头开始匹配
re.search 匹配包含
re.findall 把所有匹配到的字符放到以列表中的元素返回
re.splitall 以匹配到的字符当做列表分隔符
re.sub 匹配字符并替换
re.I(re.IGNORECASE): 忽略大小写(括号内是完整写法,下同)
几个匹配模式
M(MULTILINE): 多行模式,改变
'^'
和
'$'
的行为(参见上图)
S(DOTALL): 点任意匹配模式,改变
'.'
的行为