python学习笔记-(九)模块
基础知识
1. 定义
模块:用来从逻辑上组织python代码(变量,函数,类,逻辑----实现一个功能),本质就是.py结尾的python文件(文件名:test.py,对应的模块就是test)
包:用来从逻辑上组织模块的,本质就是一个目录(必须带有一个__init__.py文件)
2. 导入方法
module_cc文件里有很多函数&变量:
import module1_name
import module1_name,module2_name
from module_cc import * #把其他模块的东西全部导入过来执行一遍
from module_cc import m1,m2,m3
from module_alex import logger as logger_alex#若导入的模块名与当前的函数名相同,则可用as对导入的模块名重命名
3. import本质
导入模块的本质就是把python文件解释一遍;
导入包的本质就是执行该包下的__init__.py文件;
4. 模块分类
python的模块又分为以下三种:
- 自定义模块
- 内置标准模块(标准库)
- 开源模块
自定义模块
1.获取当前文件的绝对路径:
| 1 2 3 4 | #如目前路径为d:\python\new\read.py;获取当前文件的绝对路径:>>> importos#导入os模块>>> dir=os.path.abspath(__file__)>>> print(dir) | 
2.获取当前文件的父级目录绝对路径:
| 1 2 3 4 | #如目前路径为d:\python\new\read.py;获取new的绝对路径:>>> importos#导入os模块>>> dir=os.path.dirname(os.path.abspath(__file__))>>> print(dir) | 
3.当前文件的父级目录的父级目录绝对路径:
| 1 2 3 4 | #如目前路径为d:\python\new\read.py;获取python的绝对路径:>>> importos #导入os模块>>> dir=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))>>> print(dir) | 
4.对于模块和自己写的程序不在同一个目录下,可以把模块的路径通过sys.path.append(路径)添加到程序中。
在程序开头加上:
| 1 2 3 4 5 6 7 8 9 10 | #如目前路径为d:\python\new\read.py;想要导入d:\python\old\read_new.py下的程序模块:>>> importos,sys>>> dir=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))#获取python目录的绝对路径>>> sys.path.append(dir)#讲python目录的路径添加到程序中#-----想要快速找到该路径,则可使用insert将要添加的目录路径插入到path前面# sys.path.insert(dir)       >>> importold fromread_new #导入read_new.py文件#在当前路径下调用read_new.py里的某个函数,如user()>>> read_new.user() | 
内置模块
1. time & datetime
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 | importtimeimportdatetime# time模块print(time.clock())    # 输出=>3.110193534902903e-07print(time.process_time())  # 输出=>0.031200199999999997# 返回当前时间戳,即1970.1.1至今的秒数print(time.time())  # 输出=>1454239454.328046# 当前系统时间print(time.ctime())    # 输出=>Sun Jan 31 19:24:14 2016# 将当前时间戳转换成字符串格式的时间print(time.ctime(time.time()))  # 输出=>Sun Jan 31 19:24:14 2016# 将时间戳转换成struct_time格式print(time.gmtime(time.time()))# time.struct_time(tm_year=2016, tm_mon=1, tm_mday=31, tm_hour=11, tm_min=24, tm_sec=14, tm_wday=6, tm_yday=31, tm_isdst=0)# 将本地时间的时间戳转换成struct_time格式print(time.localtime(time.time()))# time.struct_time(tm_year=2016, tm_mon=1, tm_mday=31, tm_hour=19, tm_min=24, tm_sec=14, tm_wday=6, tm_yday=31, tm_isdst=0)# 与上面的相反,将struct_time格式转回成时间戳格式。print(time.mktime(time.localtime()))    # 输出=>1454239454.0# sleep# time.sleep(4)# 将struct_time格式转成指定的字符串格式print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time())))  # 输出=>2016-02-01 13:53:22# 将字符串格式转成struct_time格式print(time.strptime("2016-02-01", "%Y-%m-%d"))# time.struct_time(tm_year=2016, tm_mon=2, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=0, tm_yday=32, tm_isdst=-1)# datetime 模块print(datetime.date.today())    # 输出=>2016-02-01print(datetime.date.fromtimestamp(time.time() -86640))    # 输出=>2016-01-31current_time =datetime.datetime.now()print(current_time)    # 输出=>2016-02-01 14:01:02.428880# 返回struct_time格式的时间print(current_time.timetuple())# time.struct_time(tm_year=2016, tm_mon=2, tm_mday=1, tm_hour=14, tm_min=1, tm_sec=41, tm_wday=0, tm_yday=32, tm_isdst=-1)# 指定替换# datetime.replace([year[, month[, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]]]])print(current_time.replace(2008, 8, 8))    # 输出=>2008-08-08 14:03:53.901093# 将字符串转换成日期格式str_to_date =datetime.datetime.strptime("2016-02-01", "%Y-%m-%d")print(str_to_date)  # 输出=>2016-02-01 00:00:00# 比现在+10dnew_date =datetime.datetime.now() +datetime.timedelta(days=10)print(new_date)    # 输出=>2016-02-11 14:46:49.158138# 比现在-10dnew_date =datetime.datetime.now() -datetime.timedelta(days=10)print(new_date)    # 输出=>2016-01-22 14:53:03.712109# 比现在+10hnew_date =datetime.datetime.now() +datetime.timedelta(hours=10)print(new_date)    # 输出=>2016-02-02 00:53:03.712109# 比现在+120snew_date =datetime.datetime.now() +datetime.timedelta(seconds=120)print(new_date)    # 输出=>2016-02-01 14:55:03.712109 | 
2. random
Python中的random模块用于生成随机数.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | importrandom #导入random模块print(random.random()) #生成一个0到1的随机浮点数 0<=n<1<br>print(random.randint(1,7))#random.randint()的函数原型为:random.randint(a, b),用于生成一个指定范围内的整数。# 其中参数a是下限,参数b是上限,生成的随机数n的范围: a <= n <= b<br>print(random.randrange(1,10,2))#random.randrange的函数原型为:random.randrange([start], stop[, step]),# 从指定范围内,按指定基数递增的集合中 获取一个随机数。如:random.randrange(1,10,2),# 结果相当于从[1, 3, 5, 7, 9]序列中获取一个随机数。<br>print(random.choice('liukuni')) #i#random.choice从序列中获取一个随机元素。# 其函数原型为:random.choice(sequence)。参数sequence表示一个有序类型。# 这里要说明一下:sequence在python不是一种特定的类型,而是泛指一系列的类型。# list, tuple, 字符串都属于sequence。有关sequence可以查看python手册数据模型这一章。# 下面是使用choice的一些例子:print(random.choice("学习Python"))#学print(random.choice(["JGood","is","a","handsome","boy"]))  #Listprint(random.choice(("Tuple","List","Dict")))   #Listprint(random.sample([1,2,3,4,5],3))    #[1, 2, 5]#random.sample的函数原型为:random.sample(sequence, k),从指定序列中随机获取指定长度的片断。sample函数不会修改原有序列。  | 
| 1 2 3 4 5 6 7 8 9 10 11 | # 生成4位随机验证码check_code =""fori inrange(4):    current =random.randrange(0, 4)    ifcurrent !=i:        temp =chr(random.randint(97, 122))    else:        temp =random.randint(0, 9)    check_code ="{}{}".format(check_code, temp)print(check_code)   # 输出=>oovf | 
3. os
Python os模块包含普遍的操作系统功能。如果你希望你的程序能够与平台无关的话,这个模块是尤为重要的。
常用方法:
1. os.name #输出字符串指示正在使用的平台。如果是window 则用'nt'表示,对于Linux/Unix用户,它是'posix'。
| 1 2 3 4 | importosprint(os.name)------打印输出------nt  | 
2. os.getcwd() #函数得到当前工作目录,即当前Python脚本工作的目录路径。
| 1 2 3 4 | importosprint(os.getcwd())------打印输出------E:\python\old | 
3. os.listdir() #列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印。
| 1 2 3 4 5 | importosprint(os.listdir())------打印输出-------['dd.json', 'eg.txt', 'read.py', '__init__.py', '__pycache__'] | 
4. os.chdir("dirname") #更改当前文件脚本目录,相当于shell下的cd
| 1 2 3 4 5 6 7 | print(os.getcwd())os.chdir(r'E:\python\new')print(os.getcwd())----打印输出-----E:\python\oldE:\python\new | 
5. os.curdir #返回当前目录(.)
6. os.pardir #返回当前目录的父级目录(..)
7. os.makedirs('dirname1\dirname2') #可生成多层递归目录
| 1 2 3 4 | importosos.makedirs(r"E:\A\B\C")#可看到E盘下生成了A文件夹,A文件夹里有B文件夹,B文件夹下有C文件夹 | 
8. os.removedirs('dirnames') #若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推
| 1 2 3 4 | importosos.removedirs(r"E:\A\B\C")#可看到E盘下的A文件夹都被删除了 | 
9. os.mkdir('dirname') #生成单级目录;相当于shell中mkdir dirname
| 1 2 | importosos.mkdir(r"E:\A") | 
10. os.rmdir('dirname') #删除单级空目录,若目录不为空则报错
11. os.remove("filename") #删除一个文件
| 1 2 | importosos.remove(r"E:\A\1.txt") | 
12. os.rename("oldname","newname") #重命名文件/目录
| 1 2 | importosos.rename(r"E:\A",r"E:\B") | 
13. os.stat('path/filename') #获取指定文件/目录信息
| 1 2 3 4 5 | importosprint(os.stat("E:\B"))------打印输出-------os.stat_result(st_mode=16895, st_ino=62205969853149254, st_dev=1526633361, st_nlink=1, st_uid=0, st_gid=0, st_size=0, st_atime=1471857944, st_mtime=1471857944, st_ctime=1471857604) | 
14. os.sep #输出操作系统特定的路径分隔符,win下为"\\",Linux下为"/"
15. os.pathsep #输出用于分割文件路径的字符串
16. os.system("bash command")  运行shell命令,直接显示
| 1 2 | importosos.system('ipconfig') | 
17. os.environ #获取系统环境变量
18. os.path.abspath(path) #返回path规范化的绝对路径
| 1 2 3 4 5 | importosprint(os.path.abspath('python'))------打印输出--------E:\python\old\python | 
19. os.path.split(path) #将path分割成目录和文件二元组返回
| 1 2 3 4 5 | importosprint(os.path.split(r'E:\python\old\eg.txt'))-----打印输出-----('E:\\python\\old', 'eg.txt') | 
20. os.path.basename(path) #返回path最后的文件名。如何path以/或\结尾,那么就会返回空值。即os.path.split(path)的第二个元素
| 1 2 3 4 5 | importosprint(os.path.basename(r'E:\python\old\eg.txt'))------打印输出-----eg.txt | 
21. os.path.exists(path) #如果path存在,返回True;如果path不存在,返回False
22. os.path.isabs(path) #如果path是绝对路径则返回True
23. os.path.isfile(path) #如果path是一个存在的文件,返回True。否则返回False
24. os.path.isdir(path) #如果path是一个存在的目录,则返回True。否则返回False
25. os.path.join(path1[, path2[, ...]]) #将多个路径组合后返回,第一个绝对路径之前的参数将被忽略
| 1 2 | importosprint(os.path.join(r'E:\python\new',r'eg.txt')) | 
26. os.path.getatime(path) #返回path所指向的文件或者目录的最后存取时间
| 1 2 3 4 5 6 7 | importos,timetime1 =os.path.getatime(r'E:\python\new')x =time.localtime(time1)print(time.strftime('%Y-%m-%d %H:%M:%S',x))-----打印时间-----2016-08-1719:09:32 | 
27. os.path.getmtime(path) #返回path所指向的文件或者目录的最后修改时间
| 1 2 3 4 | importos,timetime1 =os.path.getmtime(r'E:\B')x =time.localtime(time1)print(time.strftime('%Y-%m-%d %H:%M:%S',x)) | 
4. sys
sys模块包括了一组非常实用的服务,内含很多函数方法和变量,用来处理Python运行时配置以及资源,从而可以与前当程序之外的系统环境交互
1. 导入模块
| 1 | importsys | 
2.重要函数变量
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | print(sys.argv) #命令行参数List,第一个元素是程序本身路径# -----打印输出------# ['E:/python/old/read.py']sys.exit(status) #退出程序,正常退出时exit(0)print(sys.version) #获取Python解释程序的版本信息#----打印输出-----# 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:01:18) [MSC v.1900 32 bit (Intel)]sys.path  #返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值print(sys.platform) #返回操作系统平台名称sys.stdin() #标准输入流sys.stdout #标准输出流。sys.stderr #标准错误流。 | 
5. shutil
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 | #! /usr/bin/env python# -*- coding: utf-8 -*-# __author__ = "Q1mi""""高级的 文件、文件夹、压缩包 处理模块"""importshutilimportos# 将文件内容(文件对象)拷贝到另一个文件中,可以指定部分拷贝# with open("D:\qimi_WorkSpace\S12\day6\\test1.txt", "rt") as f1, open("D:\qimi_WorkSpace\S12\day6\\test2.txt", "at")as f2:#     shutil.copyfileobj(fsrc=f1, fdst=f2)# 拷贝文件# shutil.copyfile(src="D:\qimi_WorkSpace\S12\day6\\test1.txt",dst="D:\qimi_WorkSpace\S12\day6\\test2.txt")# 仅拷贝权限。内容、组、用户均不变# print(os.stat("D:\qimi_WorkSpace\S12\day6\\test2.txt"))# shutil.copymode(src="D:\qimi_WorkSpace\S12\day6\\test1.txt", dst="D:\qimi_WorkSpace\S12\day6\\test2.txt")# print(os.stat("D:\qimi_WorkSpace\S12\day6\\test2.txt"))# # 拷贝状态的信息,包括:mode bits, atime, mtime, flags# shutil.copystat(src=,dst=)## # 拷贝文件和权限# shutil.copy(src, dst)# 拷贝文件和状态信息# shutil.copy2(src,dst)# 递归的去拷贝文件# shutil.ignore_patterns(*patterns)# shutil.copytree(src, dst, symlinks=False, ignore=None)# 递归的去删除文件# shutil.rmtree(path[, ignore_errors[, onerror]])# 递归的去移动文件# shutil.move(src, dst)# 创建压缩包并返回文件路径,例如:zip、tar# shutil.make_archive(base_name, format,...)## base_name: 压缩包的文件名,也可以是压缩包的路径。只是文件名时,则保存至当前目录,否则保存至指定路径,# 如:www                        =>保存至当前路径# 如:/Users/wupeiqi/www =>保存至/Users/wupeiqi/# format:    压缩包种类,“zip”, “tar”, “bztar”,“gztar”# root_dir:    要压缩的文件夹路径(默认当前目录)# owner:    用户,默认当前用户# group:    组,默认当前组# logger:    用于记录日志,通常是logging.Logger对象# 将D:\qimi_WorkSpace\S12\day6目录下的文件打包成test.tar.gz,放置在当前目录et =shutil.make_archive("test", 'gztar', root_dir='D:\\qimi_WorkSpace\\S12\\day6')# shutil模块对压缩包的处理是调用ZipFile和TarFile两个模块来进行的# zipfile模块importzipfile# 压缩z =zipfile.ZipFile('test.zip', 'w')z.write('a.log')z.write('a.data')z.close()# 解压z =zipfile.ZipFile('test.zip', 'r')z.extractall()z.close()# tarfile模块importtarfile# 压缩tar =tarfile.open('test.tar','w')tar.add('D:\\qimi_WorkSpace\\S12\\day6\\test1.tar', arcname='test1.tar')tar.add('D:\\qimi_WorkSpace\\S12\\day6\\test2.tar', arcname='test2.tar')tar.close()# 解压tar =tarfile.open('test.tar','r')tar.extractall()  # 可设置解压地址tar.close() | 
6. json & picle
见上篇文章,这里不再概述
7. shelve
shelve模块是一个简单的k,v将内存数据通过文件持久化的模块,可以持久化任何pickle可支持的python数据格式
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | importshelve  d =shelve.open('shelve_test') #打开一个文件  classTest(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() | 
8. xml处理
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | #! /usr/bin/env python# -*- coding: utf-8 -*-# __author__ = "Q1mi""""xml模块的练习"""importxml.etree.ElementTree as ET# 解析xml文件tree =ET.parse("test.xml")# 获取根root =tree.getroot()print(root.tag)# 遍历xml文档forchild inroot:    print(child.tag, child.attrib)    fori inchild:        print(i.tag, i.text)# 只遍历year节点fori inroot.iter("year"):    print(i.tag, i.text)# 修改和删除xml文件tree =ET.parse("test2.xml")root =tree.getroot()  | 
9. yaml处理
略。。。
10. configparser
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 | #! /usr/bin/env python# -*- coding: utf-8 -*-# __author__ = "Q1mi""""configparser 练习"""importconfigparser# 写一个配置文件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 parsertopsecret['ForwardX11'] ='no'# same hereconfig['DEFAULT']['ForwardX11'] ='yes'with open('example.ini', 'w') as configfile:    config.write(configfile)# 读配置文件config =configparser.ConfigParser()print(config.sections())a =config.read("test.cfg")print(a)print(config.sections())print("bitbucket.org"inconfig.sections())print(config["bitbucket.org"]["user"])forkey inconfig["bitbucket.org"]:    print(key, config["bitbucket.org"][key])# 增删改查config =configparser.ConfigParser()config.read("test.cfg")sec =config.sections()print(sec)options =config.options("bitbucket.org")print(options)item_list =config.items("bitbucket.org")print(item_list)val =config.get("bitbucket.org", "compressionlevel")print(val)val =config.getint("bitbucket.org", "compressionlevel")print(val)# 改写config.remove_section("bitbucket.org")config.write(open("test2.cfg", "w"))sec =config.has_section("bitbuckrt.org")print(sec)config.add_section("bitbucket.org")sec =config.has_section("bitbuckrt.org")print(sec)config.write(open("test2.cfg", "w"))config.set("bitbucket.org", 'k1', "11111")config.write(open("test2.cfg", "w"))config.remove_option("topsecret.server.com", "port")config.write(open("test2.cfg", "w"))  | 
11. hashlib
用于加密相关的操作,3.x里代替了md5模块和sha模块,主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 算法
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | importhashlib m =hashlib.md5()m.update(b"Hello")m.update(b"It's me")print(m.digest())m.update(b"It's been a long time since last time we ...") print(m.digest()) #2进制格式hashprint(len(m.hexdigest())) #16进制格式hash'''def digest(self, *args, **kwargs): # real signature unknown    """ Return the digest value as a string of binary data. """    pass def hexdigest(self, *args, **kwargs): # real signature unknown    """ Return the digest value as a string of hexadecimal digits. """    pass '''importhashlib # ######## md5 ######## hash=hashlib.md5()hash.update('admin')print(hash.hexdigest()) # ######## sha1 ######## hash=hashlib.sha1()hash.update('admin')print(hash.hexdigest()) # ######## sha256 ######## hash=hashlib.sha256()hash.update('admin')print(hash.hexdigest())  # ######## sha384 ######## hash=hashlib.sha384()hash.update('admin')print(hash.hexdigest()) # ######## sha512 ######## hash=hashlib.sha512()hash.update('admin')print(hash.hexdigest()) | 
12. re正则表达式
开源模块
暂略
 
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号