1.模块和包

●模块定义:用来从逻辑上组织python代码(变量,函数,类,逻辑:实现一个功能),本质就是.py结尾的python文件(文件名test.py,对应的模块名:test)

●包定义:用来从逻辑上组件模块的,本质就是一个目录(必须带有一个__init__.py文件)


2.模块和包导入本质

●导入模块的本质就是把python文件解释一遍

● 导入包的本质就是执行该包下的__init__.py文件;如果要导入包下面的模块:需要先导入包,然后包下的__init__.py文件中再导入该包下的模块


3.导入模块

importmodule_name#导入一个模块importmodule1_name,module2_name#导入多个模块module_name.logger()#执行模块里的函数modele_name.var#调用模块里的变量frommodule_nameimportmethod1method2frommodule_nameimport*#导入模块的所有方法,不建议用logger()#直接调用模块里的方法,不用模块名加点frommodule_nameimportloggeraslogger_feng#导入将模块里的logger方法并改名


4.导入不同包(目录)下的python模块

importos,sys#print(__file__)#动态获取当前文件相当路径#print(os.path.abspath(__file__))#动态获取当前文件绝对路径#print(os.path.dirname(os.path.abspath(__file__))#动态获取当前文件父目录路径PATH=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))#这里获取到的是ATM这个目录的绝对路径sys.path.append(PATH)#将获取到的绝对路径加到环境变量fromcoreimportmain#从core目录下importmainmain.name("fengxiaoli")#调用main里的函数name

5.time模块

python中通常时间的表示

●时间戳

●格式化的时间字符串

●元组时间

●时间戳-->元组时间

>>>x=time.time()#获取当前时间戳>>>time.gmtime(x)#将当前时间戳转化为utc时间元组time.struct_time(tm_year=2018,tm_mon=2,tm_mday=4,tm_hour=10,tm_min=4,tm_sec=22,tm_wday=6,tm_yday=35,tm_isdst=0)>>>time.localtime(x)#将当前时间戳转化为本地时间(utc+8)元组time.struct_time(tm_year=2018,tm_mon=2,tm_mday=4,tm_hour=18,tm_min=4,tm_sec=22,tm_wday=6,tm_yday=35,tm_isdst=0)>>>x1=time.localtime(x)>>>x1.tm_year#获取元组时间2018>>>x1.tm_mon2


●元组时间-->时间戳

>>>x1time.struct_time(tm_year=2018,tm_mon=2,tm_mday=4,tm_hour=18,tm_min=4,tm_sec=22,tm_wday=6,tm_yday=35,tm_isdst=0)>>>time.mktime(x1)1517738662.0

●元组时间-->自定义格式化字符串时间

>>>x1time.struct_time(tm_year=2018,tm_mon=2,tm_mday=4,tm_hour=18,tm_min=4,tm_sec=22,tm_wday=6,tm_yday=35,tm_isdst=0)>>>time.strftime("%Y-%m-%d%H:%M:%S",x1)'2018-02-0418:04:22'

●自定义格式化字符串时间-->元组时间

>>>help(time.strptime)#查看strptime帮助strptime(...)strptime(string,format)->struct_time>>>time.strptime("2018-02-0418:04:22","%Y-%m-%d%H:%M:%S")time.struct_time(tm_year=2018,tm_mon=2,tm_mday=4,tm_hour=18,tm_min=4,tm_sec=22,tm_wday=6,tm_yday=35,tm_isdst=-1)


●时间戳-->格式化字符串

>>>x1517738662.821426>>>time.ctime(x)'SunFeb418:04:222018'

●元组-->格式化字符串

>>>x1time.struct_time(tm_year=2018,tm_mon=2,tm_mday=4,tm_hour=18,tm_min=4,tm_sec=22,tm_wday=6,tm_yday=35,tm_isdst=0)>>>time.asctime(x1)'SunFeb418:04:222018'


●time模块其他方法

>>>importtime>>>time.timezone#标准时间(utc)和本地时间(utc+8)相差多少秒-28800#这里是本地时间比标准时间早28800秒,也就是早8小时,也就是中国为utc+8时区>>>28800/36008.0>>>time.altzone#标准时间和夏令时相差多少-32400>>>time.daylight#判断是否是夏令时0>>>time.clock()#当运行time.clock()开始,返回一个时间1.0263524545646598e-05>>>time.clock()2.1054247858986015>>>time.clock()3.8245134020248224>>>time.clock()6.940938975648932>>>time.clock()15.189280774964526>>>time.sleep(2)#程序睡2秒>>>time.sleep(1)>>>time.time()#返回一个时间戳,该时间戳是从1970到现在多少秒1517737506.325569>>>x=time.time()>>>x/3600/24/36548.12714301673213>>>1970+482018

6.datetime模块

>>>importdatetime>>>print(datetime.datetime.now())#获取当前时间2018-02-0418:37:25.319604>>>print(datetime.date.fromtimestamp(time.time()))#将时间戳改为格式化字符串2018-02-04>>>print(datetime.datetime.now()+datetime.timedelta(3))#当前时间+3天2018-02-0718:40:59.8228>>>print(datetime.datetime.now()+datetime.timedelta(-3))#当前时间-3天2018-02-0118:41:06.402249>>>print(datetime.datetime.now()+datetime.timedelta(hours=3))#当前时间加3小时2018-02-0421:41:29.079546>>>print(datetime.datetime.now()+datetime.timedelta(minutes=-3))#当前时间减3分钟2018-02-0418:38:40.102177>>>c_time=datetime.datetime.now()>>>print(c_time.replace(minute=3,hour=2))#更改时间2018-02-0402:03:47.909055

7.random模块

#随机浮点数>>>importrandom>>>random.random()#生成一个0-1的随机浮点数0.7370268365256588>>>random.uniform(1,3)#随机打印1-3直接的浮点数2.907184937455974>>>random.uniform(1,5)3.1441005290312556#随机整数>>>random.randint(1,5)#生成一个1-5的随机整数,包括1和55>>>random.randint(1,5)2#随机选取0-100间的偶数>>>random.randrange(0,101,2)6>>>random.randrange(1,5)#生成一个1-4的随机整数,不包括53>>>random.randrange(1,5)4#随机字符>>>random.choice("hello")#随机打印一个前面对象的元素'o'>>>random.choice([1,2,3,4])2#多个字符选取特定数量字符>>>random.sample("hello",2)#指定个数随机打印前面对象元素['l','o']>>>random.sample([1,2,3,4],2)[3,4]#洗牌>>>x=[1,2,3,4,5]>>>random.shuffle(x)#将列表随机打乱>>>print(x)[3,1,2,4,5]#验证码,生成4位随机验证码importrandomn=4checkcode=""foriinrange(n):current=random.randrange(0,n)ifi<current:tmp=random.randint(0,9)elifi==current:tmp=chr(random.randrange(97,122))else:tmp=chr(random.randrange(65,90))checkcode+=str(tmp)print(checkcode)

8.os模块

#提供对操作系统进行调用的接口#对目录操作os.getcwd()#获取当前工作目录,即当前python脚本工作的目录路径os.chdir("dirname")#改变当前脚本工作目录;相当于shell下cdos.curdir#返回当前目录:('.')os.pardir#获取当前目录的父目录字符串名:('..')os.makedirs('dirname1/dirname2')#可生成多层递归目录os.removedirs('dirname1')#若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推os.mkdir('dirname')#生成单级目录;相当于shell中mkdirdirnameos.rmdir('dirname')#删除单级空目录,若目录不为空则无法删除,报错;相当于shell中rmdirdirnameos.listdir('dirname')#列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印#对文件操作os.remove()#删除一个文件os.rename("oldname","newname")#重命名文件/目录os.stat('path/filename')#获取文件/目录信息os.sep#输出操作系统特定的路径分隔符,win下为"\\",Linux下为"/"os.linesep#输出当前平台使用的行终止符,win下为"\r\n",Linux下为"\n"os.pathsep#输出用于分割文件路径的字符串os.name#输出字符串指示当前使用平台。win->'nt';Linux->'posix'os.system("bashcommand")#运行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不存在,返回Falseos.path.isabs(path)#如果path是绝对路径,返回Trueos.path.isfile(path)#如果path是一个存在的文件,返回True。否则返回Falseos.path.isdir(path)#如果path是一个存在的目录,则返回True。否则返回Falseos.path.join(path2[,path3[,...]])#将多个路径组合后返回,第一个绝对路径之前的参数将被忽略os.path.getatime(path)#返回path所指向的文件或者目录的最后存取时间os.path.getmtime(path)#返回path所指向的文件或者目录的最后修改时

9.sys模块

importsysprint(sys.argv)#以list格式返回该脚本参数,返回的第一个参数是执行该脚本相当路径如:pythontest.py123['test.py','1','2','3']sys.exit(n)#退出程序,正常退出时exit(0)sys.version#获取python版本sys.path#返回模块搜索路径,初始化时使用pythonpath环境变量的值sys.platform#返回操作系统平台sys.stdout.write("--")#标准输出到屏幕

10.shutil模块

#高级的文件、文件夹、压缩包处理模块importshutilf1=open("file1","r",encoding="utf-8")f2=open("file2","w",encoding="utf-8")shutil.copyfileobj(f1,f2)#复制文件1内容到文件2,需要自己打开关闭文件shutil.copyfile("file1","file2")#复制文件1内容到文件2,不需要自己打开关闭文件shutil.copymode("file1","file2")#仅拷贝权限,内容,组,用户均不变shutil.copystat("file1","file2")#拷贝状态的信息,包括modebits,atime,mtime,flagsshutil.copy("file1","file2")#拷贝文件和权限shutil.copy2("file1","file2")#拷贝文件和状态信息shutil.copytree("srcdir","dstdir")#递归的拷贝文件shutil.rmtree("dstdir")#递归删除文件shutil.move("src","dst")#递归的去移动文件shutil.make_archive("base_name",format,...)#创建压缩包并返回文件路径,例如:zip、tarbase_name:压缩包的文件名,也可以是压缩包的路径。只是文件名时,则保存至当前目录,否则保存至指定路径。format:压缩包种类,“zip”,“tar”,“bztar”,“gztar”root_dir:要压缩的文件夹路径(默认当前目录)owner:用户,默认当前用户group:组,默认当前组logger:用于记录日志,通常是logging.Logger对象


11.zipfile模块

importzipfileimpotos#压缩单个文件importzipfileimportoswithzipfile.ZipFile('test.zip','w')asz:z.write('log.txt')#压缩某个目录下所有文件defcompress_file(zipfilename,dirname):#zipfilename是压缩包名字,dirname是要打包的目录/文件ifos.path.isfile(dirname):withzipfile.ZipFile(zipfilename,'w')asz:z.write(dirname)else:withzipfile.ZipFile(zipfilename,'w')asz:forroot,dirs,filesinos.walk(dirname):#这里用到了os.walk遍历目录下的文件,详情参考os的walk方法forsingle_fileinfiles:ifsingle_file!=zipfilename:filepath=os.path.join(root,single_file)z.write(filepath)compress_file('a.zip','.')#执行函数#添加文件到已有的zip包中defaddfile(zipfilename,dirname):ifos.path.isfile(dirname):withzipfile.ZipFile(zipfilename,'a')asz:z.write(dirname)else:withzipfile.ZipFile(zipfilename,'a')asz:forroot,dirs,filesinos.walk(dirname):forsingle_fileinfiles:ifsingle_file!=zipfilename:filepath=os.path.join(root,single_file)z.write(filepath)addfile('a.zip','test.txt')#查看压缩包中的文件defviewfile(zipfilename):withzipfile.ZipFile(zipfilename,'r')asz:print(z.namelist())viewfile('a.zip')#解压withzipfile.ZipFile('test.zip','r')asz:print(z.namelist())#查看压缩包中的文件列表#print(z.read(z.namelist()[0]))#读出来压缩包中的第一个文件的内容打印到屏幕,也可保存到文件中z.extractall('C:\\Users\\Administrator\\PycharmProjects\\aaa')#解压,可设置解压路径#z.extract('log.txt')#解压,可选择解压压缩包中的某个文件#z.extractall()#解压全部


12.tarfile模块

importtarfileimportos#压缩文件withtarfile.open('a.tar','w')astar:tar.add('log.log',arcname='log.log')tar.add('test.txt',arcname='test.txt')#解压文件withtarfile.open('a.tar','r')astar:print(tar.getmembers())#查看压缩包内文件成员#tar.extract('test.txt')#可选择解压某个文件#tar.extractall('ccc')#可设置解压路径tar.extractall()#解压全部#压缩某个目录下所有文件defcompress_file(tarfilename,dirname):#tarfilename是压缩包名字,dirname是要打包的目录ifos.path.isfile(dirname):withtarfile.open(tarfilename,'w')astar:tar.add(dirname)else:withtarfile.open(tarfilename,'w')astar:forroot,dirs,filesinos.walk(dirname):forsingle_fileinfiles:#ifsingle_file!=tarfilename:filepath=os.path.join(root,single_file)tar.add(filepath)compress_file('test.tar','test.txt')compress_file('t.tar','.')#添加文件到已有的tar包中defaddfile(tarfilename,dirname):#tarfilename是压缩包名字,dirname是要打包的目录ifos.path.isfile(dirname):withtarfile.open(tarfilename,'a')astar:tar.add(dirname)else:withtarfile.open(tarfilename,'a')astar:forroot,dirs,filesinos.walk(dirname):forsingle_fileinfiles:#ifsingle_file!=tarfilename:filepath=os.path.join(root,single_file)tar.add(filepath)addfile('t.tar','ttt.txt')addfile('t.tar','ttt')


13.xml模块

importxml.etree.ElementTreeasET#导入xml模块并取别名tree=ET.parse("xml_test.xml")#找到xml文件内存地址root=tree.getroot()#找到xml文件根内存地址print(root.tag)#打印xml文件根标签#遍历xml文档forchildinroot:print(child.tag,child.attrib)foriinchild:print(i.tag,i.text,i.attrib)#只遍历year节点fornodeinroot.iter('year'):print(node.tag,node.text)#修改和删除xml文档内容importxml.etree.ElementTreeasETtree=ET.parse("xmltest.xml")root=tree.getroot()#修改fornodeinroot.iter('year'):new_year=int(node.text)+1node.text=str(new_year)node.set("updated","yes")tree.write("xmltest.xml")#删除nodeforcountryinroot.findall('country'):rank=int(country.find('rank').text)ifrank>50:root.remove(country)tree.write('output.xml')#自己创建xml文件importxml.etree.ElementTreeasETnew_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)#打印生成的格式


14.configparser模块

#将字符写为配置文件的形式importconfigparserconfig=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['HostPort']='50022'#mutatestheparsertopsecret['ForwardX11']='no'#samehereconfig['DEFAULT']['ForwardX11']='yes'withopen('example.ini','w')asconfigfile:config.write(configfile)#读configparser文件importconfigparserconf=configparser.ConfigParser()conf.read("example.ini")#print(conf.defaults())#print(conf["bitbucket.org"]["user"])##print(conf.sections())foriinconf["topsecret.server.com"]:print(i)#删除importconfigparserconf=configparser.ConfigParser()conf.read("example.ini")sec=conf.remove_section("bitbucket.org")conf.write(open("example.cfg","w"))#改写importconfigparserconf=configparser.ConfigParser()conf.read("example.ini")sec=conf.remove_section("bitbucket.org")sec=conf.add_section("fengxiaoli.org")sec=conf.set("fengxiaoli.org","k1","111")conf.write(open("example.cfg","w"))


14.re模块

# re.match 从头开始匹配 ,返回一个

# re.search 匹配包含,返回一个

# re.findall 把所有匹配到的字符放到以列表中的元素返回,返回所有

# re.splitall 以匹配到的字符当做列表分隔符

# re.sub 匹配字符并替换

importre#match方法c="chen234feng3252cxasfgj54gvf"res1=re.match("chen",c)res2=re.match("^chen\d+",c)res3=re.match(".+",c)#res4=re.match("cx",c)#匹配不到cx,因为re.match只能从头开始匹配print(res1.group())print(res2.group())print(res3.group())#print(res4.group())#search方法c="chen234fengdfasfcx3252cxasfgj54gvf"res1=re.search("cx",c)res2=re.search("feng.*cx",c)res3=re.search("^chen.+cx",c)res4=re.search("feng[a-z]+cx",c)res5=re.search("[0-9]{3}",c)#匹配连续出现3次数字的字符res6=re.search("[0-9]{1,3}",c)#匹配连续出现数字,1次到3次的字符,re.search只能返回一个res7=re.search("(abc){2}","fengabcabcffcxabc")#将abc分组,匹配连续出现两次的abcprint(res1.group())print(res2.group())print(res3.group())print(res4.group())print(res5.group())print(res6.group())print(res7.group())#分组匹配'(?P<name>...)'res10=re.search("(?P<id>[0-9]+)(?P<name>[a-zA-Z]{4})",c).groupdict()print(res10)#输出{'id':'234','name':'feng'}res11=re.search("(?P<province>[0-9]{4})(?P<city>[0-9]{2})(?P<birthday>[0-9]{4})","371481199306143242").groupdict()#结果print(res11)#{'province':'3714','city':'81','birthday':'1993'}#findall方法c="c1hen234fengdfas1fcx3252cxasfgj54gvf"res1=re.findall("cx",c)res2=re.findall("feng|cx",c)res6=re.findall("[0-9]{1,3}",c)print(res1)print(res2)print(res6)#split方法res=re.split("[0-9]","dsf34dsf46kjl6")#按指定字符分割res1=re.split(":","dsf:34ds:f46kjl6")print(res)print(res1)#sub方法res=re.sub("[0-9]+","AAA","afd454dffb56756sdg11feng")#将匹配的字符替换为指定字符res1=re.sub("[0-9]+","AAA","afd454dffb56756sdg11feng",count=2)#指定替换的次数print(res)print(res1)注:#re.I(re.IGNORECASE):忽略大小写(括号内是完整写法,下同)#M(MULTILINE):多行模式,改变'^'和'$'的行为#S(DOTALL):点任意匹配模式,改变'.'的行为#res1=re.search("fengxiaoli","\nFengXiaoLi123Cx456\nKdf564",flags=re.I)#忽略大小写#res1=re.search("^Feng","\nFengXiaoLi123Cx456\nKdf564",flags=re.M)#res1=re.search("Cx.+564","\nFengXiaoLi123Cx456\nKdf564",flags=re.S)#默认点不能匹配\n,加上re.S后可以print(res1.group())