python基础——模块

来源:互联网 发布:线切割编程要证明的 编辑:程序博客网 时间:2024/06/10 22:17

模块:用来从逻辑上组织python代码(变量,函数,类,逻辑:实现一个功能),本质就是.py结尾的python文件(文件名:test.py,对应的模块名:test)
导入模块的本质就是把python文件解释一遍,即把该模块中所有的代码赋值给该模块名
包:用来从逻辑上组织模块的,本质就是一个目录(必须带有一个init.py文件),导入包的本质就是执行该包下的init.py文件

跨包调用模块举例说明
在module_test包的main模块中调用package_test包中的test1模块。
目录结构

main模块中的代码

import osimport sysdir_path=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))sys.path.append(dir_path)#添加package_test的绝对路径import package_test#只有添加了路径,才能使之被导入package_test.test1.log()#因为在导入package_test包的时候执行的是__init__,而在__init__中导入了test1模块,所以可以直接这样调用

init 模块中的代码

from . import test1 #导入包的时候就是执行__init__文件,所以在该文件中需要导入test模块,才能使其他包中的模块调用该包中的test1模块

test1模块中的代码

def log():    print("in the test1")

模块的分类:
1、标准库
2、开源模块
3、自定义模块

标准库模块

#标准库模块:time和datatime#模块time的方法如下,时间分三种格式:时间戳、格式化的字符串、struct_time(tuple)import timeimport datetime#print(time.time())#时间戳,意思就是从1970年到目前为止的秒数#print(time.sleep(2))#延时#print(time.gmtime())#从时间戳转换成struct_time格式,不传就是将本地时间格式化成元组形式的,UTC时区的(标准时间),也就是把总共多少秒换成年、月、日……#print(time.localtime())#从时间戳转换成当地的时间元组格式,以本地时区格式为准#print(time.localtime().tm_year)#获取元组中的年#print(time.mktime(time.localtime()))#将元组形式转换成时间戳的形式#print(time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()))#将元组格式的时间转成自定义的时间格式#print(time.strptime("2017-09-02 16:38:02","%Y-%m-%d %H:%M:%S"))#将自定义时间转换成格式化数组形式#print(time.asctime())#把元组时间转换成Sat Sep  2 16:50:56 2017格式,没传值默认是本地时间#print(time.ctime())#把时间戳转换成Sat Sep  2 16:50:56 2017格式,没传值默认是本地时间#print(datetime.datetime.now())#获取当前时间print(datetime.datetime.now()+datetime.timedelta(3))#获取3天后的时间print(datetime.datetime.now()+datetime.timedelta(3))#获取3天前的时间print(datetime.datetime.now()+datetime.timedelta(hours=3))#获取3小时后的时间print(datetime.datetime.now().replace(minute=3,hour=2))#替换当前的时间

random模块

import random#print(random.random())#用于生成一个0到1的随机浮点数#print(random.randint(1,7))#用于生成一个指定范围内的整数#print(random.randrange(1,10))#从1到10生成一个随机数,不包含10,步长默认为1#print(random.choice('hello'))#从指定序列中随机产生一个,序列可以是字符串、列表、数组等#print(random.sample('hello',2))#从指定序列中随机取两个#print(random.uniform(1,10))#从指定的区间中随机取出一个浮点数'''l=[2,3,4,5,6,7]random.shuffle(l)#将顺序打乱,随机洗牌print(l)'''

OS模块

import os#print(os.getcwd())#获取当前路径#os.chdir("C:\\Users")#切换当前路径#os.chdir(r"C:\Users")#切换当前路径#print(os.curdir)#返回当前目录#print(os.pardir)#返回上一级目录#os.makedirs(r"C:\a\b\c\d")#递归的创建目录#os.removedirs(r"C:\a\b\c\d")#递归的删除空目录#os.mkdir(r"D:\a")#创建单级目录#os.rmdir(r"D:\a")#删除所有目录,不管是否为空#os.listdir(".")#列出该目录下的所有内容,包括隐藏文件并以列表的方式打印#os.rename("oldname","newname")#重命名文件/目录#print(os.stat("."))#获取文件/目录信息#print(os.sep)#输出操作系统特定的路径分隔符,win下为"\\",Linus下为"\"#print(os.linesep)#输出当前平台使用的行终止符,win下为"\t\n",Linus下为"\n"#print(os.pathsep)#输出用于分割文件路径的字符串#print(os.environ)#输出环境变量#print(os.name)#输出字符串指示当前使用平台的名称#print(os.system("ipconfig"))#运行系统命令#print(os.path.abspath("os_test.py"))#获取文件的绝对路径#print(os.path.split(r"C:\a\b\c\test.txt"))#将目录名和文件名分隔开,以二元组的形式返回#print(os.path.dirname(r"C:\a\b\c\test.txt"))#获取目录名#print(os.path.basename(r"C:\a\b\c\test.txt"))#获取目录下的文件名#print(os.path.exists(r"C:"))#判断路径是否存在#print(os.path.isabs(r"C:\a"))#判断是否为绝对路径#print(os.path.isfile(r"C:"))#判断是否为文件#print(os.path.join(r"C:",r"\c",r"\a.txt"))#将多个路径组合返回,第一个绝对路径之前的参数将被忽略#print(os.path.getatime(path))#返回path所指向的文件或者目录的最后存取时间戳#print(os.path.getmtime(path))#返回path所指向的文件或者目录的最后修改时间戳

sys模块

import sys#print(sys.argv)#命令行参数list,第一个元素是程序本身路径#sys.exit(0)#退出程序,正常退出时exit(0)#sys.version#获取python解释程序的版本信息#print(sys.maxunicode)#最大的Int值#print(sys.path)#返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值print(sys.platform)#返回操作系统平台名称

shutil模块

import shutil'''f1=open("本节笔记",encoding="utf-8")f2=open("笔记2","w",encoding="utf-8")shutil.copyfileobj(f1,f2)#将文件内容拷贝到另一个文件中,可以部分内容''''''拷贝文件shutil.copyfile("笔记2","笔记3")#拷贝文件,将笔记2拷贝到笔记3''''''递归拷贝文件,即拷贝目录shutil.copytree(source,destination,ignore=ignore_pattern("*.pyc","tmp*"))''''''删除目录shutil.rmtree("source")''''''压缩目录shutil.make_archive("shutil_archive-test","zip","E:\c++")'''import zipfile'''把文件p_test.py和笔记2都压缩到day3.zipz=zipfile.ZipFile("day3.zip","w")z.write("p_test.py")print("-----------")z.write("笔记2")z.close()''''''解压所有的文件z=zipfile.ZipFile("day3.zip","r")z.extractall()z.close()'''

shelve模块

'''shelve模块持久化各种类型数据'''import shelveimport datetimed=shelve.open("shelve_test")#打开一个文件info={"age":22,"job":"it"}name=["Jorocco","rain","test"]d["name"]=name#持久化一个列表d["info"]=info#持久化一个字典d["data"]=datetime.datetime.now()d.close()

读数据

import shelveimport datetimed=shelve.open('shelve_test')print(d.get("name"))print(d.get("info"))print(d.get("date"))

xml模块
xml_test.xml

<data>    <country name="Liechtenstein">        <rank updated="yes">2</rank>        <year updated="yes">2009</year>        <gdppc>141100</gdppc>        <neighbor direction="E" name="Austria" />        <neighbor direction="W" name="Switzerland" />    </country>    <country name="Singapore">        <rank updated="yes">5</rank>        <year updated="yes">2012</year>        <gdppc>59900</gdppc>        <neighbor direction="N" name="Malaysia" />    </country>    <country name="Panama">        <rank updated="yes">69</rank>        <year updated="yes">2012</year>        <gdppc>13600</gdppc>        <neighbor direction="W" name="Costa Rica" />        <neighbor direction="E" name="Colombia" />    </country></data>

获取xml文件中的内容

import xml.etree.ElementTree as ETtree = ET.parse("xml_test.xml")root = tree.getroot()#获取地址print(root.tag)#获取第一个标签#遍历xml文档for child in root:    print(child.tag, child.attrib)#child.tag获取标签 child.attrib获取属性    for i in child:        print(i.tag,i.text,i.attrib)#i.text获取值#只遍历year 节点for node in root.iter('year'):#取出指定的节点    print(node.tag,node.text)

增删改xml文件

import xml.etree.ElementTree as ETtree = ET.parse("xml_test.xml")root = tree.getroot()# #修改# for node in root.iter('year'):#     new_year = int(node.text) + 1#     node.text = str(new_year)#添加值#     node.set("updated","yes")#添加属性## tree.write("xml_test.xml")#删除nodefor country in root.findall('country'):   rank = int(country.find('rank').text)#获取(查找)country标签下的rank的值   if rank > 50:     root.remove(country)#删除country标签下的所有东西tree.write('output.xml')

创建xml文件

import xml.etree.ElementTree as ETnew_xml = ET.Element("personinfolist")#根节点(标签)personinfo = ET.SubElement(new_xml,"personinfo",attrib={"enrolled":"yes"})#创建personinfolist根节点的子节点personinfo与属性name = ET.SubElement(personinfo,"age",attrib={"checked":"no"})sex = ET.SubElement(personinfo,"sex")age.text = '33'personinfo2 = ET.SubElement(new_xml,"personinfo",attrib={"enrolled":"no"})age = ET.SubElement(personinfo2,"age")age.text = '19'et = ET.ElementTree(new_xml) #生成文档对象et.write("test.xml", encoding="utf-8",xml_declaration=True)#xml_declaration声明为xml格式ET.dump(new_xml) #打印生成的格式

ConfigParser模块
用于生成和修改常见配置文档,当前模块的名称在 python 3.x 版本中变更为 configparser

example.ini文件

[DEFAULT]ServerAliveInterval = 45Compression = yesCompressionLevel = 9ForwardX11 = yes[bitbucket.org]User = hg[topsecret.server.com]Port = 50022ForwardX11 = no

用python生成上面的文档

import configparserconfig = 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 parsertopsecret['ForwardX11'] = 'no'  # same hereconfig['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']>>> 'bitbucket.org' in configTrue>>> 'bytebong.com' in configFalse>>> 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)...usercompressionlevelserveraliveintervalcompressionforwardx11>>> config['bitbucket.org']['ForwardX11']'yes'

hashlib模块
用于加密用

import hashlibm=hashlib.md5()m.update(b"Hello")print(m.hexdigest())#对Hello用md5加密后的16进制值m.update(b"It's me")print(m.hexdigest())#对HelloIt's me用md5加密后的16进制值m2=hashlib.md5()m2.update("HelloIt's me 天王盖地虎".encode(encoding="utf-8"))#有中文的需要转码print(m2.hexdigest())

正则表达式模块

import re#match始终是从字符串开头开始匹配,匹配到了一个就返回#res=re.match(".","Chen321double123")#.匹配出换行符外的任意字符#res=re.match("^d","Chen321double123")#^匹配以字母C开头的字符#search是从整个字符串开始匹配,匹配到了一个就返回#res=re.search("d[a-z]+e","Chen321double123")#匹配以d开头,e结尾的小写字母字符串#?匹配它前面的一个字符一次或零次# res1=re.search("aaa?","aalexaaa")#aa可以匹配得到,这里匹配?签的a零次# res2=re.search("aaa?","alexaaa")#前面的a匹配不到,这里不管是匹配?前的a一次(即aaa),还是零次(aa),都不能与alexaaa中的第一个a匹配到#res=re.search("[0-9]{3}","aa1x2a345aa")#{3}匹配前面的3次,即匹配0-93个数字#res=re.search("abc|ABC","ABCBabcCD")#匹配abc或ABC,先匹配到ABC,所以返回ABC#res=re.search("(abc){2}(\|\|=){2}","abcabc||=||=")#分组匹配#res=re.search("\A[0-9]+[a-z]\Z","123a")#匹配以0-9数字开头和以a-z字母结尾的字符串#res=re.search("(?P<province>[0-9]{4})(?P<city>[0-9]{2})(?P<birthday>[0-9]{4})","371481199306143242").groupdict()#findall从整个字符串开始匹配,返回所有符合条件的#res=re.findall("ab+","ab+abab+abb+aab")#匹配前一个字符一次或多次#res=re.findall("[0-9]{1,3}","aa1x2a345a22a")#匹配1-3个在0-9之间的数字#将字符串分割成列表#res=re.split("[0-9]","abc12de3f45GH")#将数字分割掉,将分割出来的字符串组成一个列表#res=re.split("[0-9]+","abc12de3f45GH")#替换字符串#res=re.sub("[0-9]+","|","abc12de3f45GH")#将数字替换成成|res=re.sub("[0-9]+","|","abc12de3f45GH",count=2)#只替换前两个符合匹配地方print(res)

模块解释
参考这里的正则表达式模块

'.'     默认匹配除\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'}