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 ew ead.py;获取当前文件的绝对路径:
>>> import os#导入os模块
>>> dir = os.path.abspath(__file__)
>>> print(dir)

2.获取当前文件的父级目录绝对路径:

1
2
3
4
#如目前路径为d:python ew ead.py;获取new的绝对路径:
>>> import os#导入os模块
>>> dir = os.path.dirname(os.path.abspath(__file__))
>>> print(dir)

3.当前文件的父级目录的父级目录绝对路径:

1
2
3
4
#如目前路径为d:python ew ead.py;获取python的绝对路径:
>>> import os #导入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 ew ead.py;想要导入d:pythonold ead_new.py下的程序模块:
>>> import os,sys
>>> dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))#获取python目录的绝对路径
>>> sys.path.append(dir)#讲python目录的路径添加到程序中
#-----想要快速找到该路径,则可使用insert将要添加的目录路径插入到path前面
# sys.path.insert(dir)       
>>> import old from read_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
import time
import datetime
 
# time模块
 
print(time.clock())    # 输出=>3.110193534902903e-07
print(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-01
 
print(datetime.date.fromtimestamp(time.time() - 86640))    # 输出=>2016-01-31
 
current_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(200888))    # 输出=>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
 
# 比现在+10d
new_date = datetime.datetime.now() + datetime.timedelta(days=10)
print(new_date)    # 输出=>2016-02-11 14:46:49.158138
 
# 比现在-10d
new_date = datetime.datetime.now() - datetime.timedelta(days=10)
print(new_date)    # 输出=>2016-01-22 14:53:03.712109
 
# 比现在+10h
new_date = datetime.datetime.now() + datetime.timedelta(hours=10)
print(new_date)    # 输出=>2016-02-02 00:53:03.712109
 
# 比现在+120s
new_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
import random #导入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"]))  #List
print(random.choice(("Tuple","List","Dict")))   #List
 
print(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 = ""
for in range(4):
    current = random.randrange(04)
    if current != i:
        temp = chr(random.randint(97122))
    else:
        temp = random.randint(09)
    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
import os
print(os.name)
------打印输出------
nt 

2. os.getcwd() #函数得到当前工作目录,即当前Python脚本工作的目录路径。

1
2
3
4
import os
print(os.getcwd())
------打印输出------
E:pythonold

3. os.listdir() #列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印。

1
2
3
4
5
import os
print(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 ew')
print(os.getcwd())
 
----打印输出-----
E:pythonold
E:python ew

5. os.curdir #返回当前目录(.)

6. os.pardir #返回当前目录的父级目录(..)

7. os.makedirs('dirname1dirname2') #可生成多层递归目录

1
2
3
4
import os
os.makedirs(r"E:ABC")
 
#可看到E盘下生成了A文件夹,A文件夹里有B文件夹,B文件夹下有C文件夹

8. os.removedirs('dirnames') #若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推

1
2
3
4
import os
os.removedirs(r"E:ABC")
 
#可看到E盘下的A文件夹都被删除了

9. os.mkdir('dirname') #生成单级目录;相当于shell中mkdir dirname

1
2
import os
os.mkdir(r"E:A")

10. os.rmdir('dirname') #删除单级空目录,若目录不为空则报错

11. os.remove("filename") #删除一个文件

1
2
import os
os.remove(r"E:A1.txt")

12. os.rename("oldname","newname") #重命名文件/目录

1
2
import os
os.rename(r"E:A",r"E:B")

13. os.stat('path/filename') #获取指定文件/目录信息

1
2
3
4
5
import os
print(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
import os
os.system('ipconfig')

17. os.environ #获取系统环境变量

18. os.path.abspath(path)  #返回path规范化的绝对路径

1
2
3
4
5
import os
print(os.path.abspath('python'))
 
------打印输出--------
E:pythonoldpython

19. os.path.split(path) #将path分割成目录和文件二元组返回

1
2
3
4
5
import os
print(os.path.split(r'E:pythonoldeg.txt'))
 
-----打印输出-----
('E:\python\old''eg.txt')

20. os.path.basename(path) #返回path最后的文件名。如何path以/或结尾,那么就会返回空值。即os.path.split(path)的第二个元素

1
2
3
4
5
import os
print(os.path.basename(r'E:pythonoldeg.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
import os
print(os.path.join(r'E:python ew',r'eg.txt'))

26. os.path.getatime(path) #返回path所指向的文件或者目录的最后存取时间

1
2
3
4
5
6
7
import os,time
time1 = os.path.getatime(r'E:python ew')
= time.localtime(time1)
print(time.strftime('%Y-%m-%d %H:%M:%S',x))
 
-----打印时间-----
2016-08-17 19:09:32

27. os.path.getmtime(path) #返回path所指向的文件或者目录的最后修改时间

1
2
3
4
import os,time
time1 = os.path.getmtime(r'E:B')
= time.localtime(time1)
print(time.strftime('%Y-%m-%d %H:%M:%S',x))

4. sys

sys模块包括了一组非常实用的服务,内含很多函数方法和变量,用来处理Python运行时配置以及资源,从而可以与前当程序之外的系统环境交互

1. 导入模块

1
import sys

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"
 
"""
高级的 文件、文件夹、压缩包 处理模块
"""
 
import shutil
import os
 
# 将文件内容(文件对象)拷贝到另一个文件中,可以指定部分拷贝
# with open("D:qimi_WorkSpaceS12day6\test1.txt", "rt") as f1, open("D:qimi_WorkSpaceS12day6\test2.txt", "at")as f2:
#     shutil.copyfileobj(fsrc=f1, fdst=f2)
 
# 拷贝文件
# shutil.copyfile(src="D:qimi_WorkSpaceS12day6\test1.txt",dst="D:qimi_WorkSpaceS12day6\test2.txt")
 
# 仅拷贝权限。内容、组、用户均不变
# print(os.stat("D:qimi_WorkSpaceS12day6\test2.txt"))
# shutil.copymode(src="D:qimi_WorkSpaceS12day6\test1.txt", dst="D:qimi_WorkSpaceS12day6\test2.txt")
# print(os.stat("D:qimi_WorkSpaceS12day6\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_WorkSpaceS12day6目录下的文件打包成test.tar.gz,放置在当前目录
et = shutil.make_archive("test"'gztar', root_dir='D:\qimi_WorkSpace\S12\day6')
 
# shutil模块对压缩包的处理是调用ZipFile和TarFile两个模块来进行的
 
# zipfile模块
import zipfile
 
# 压缩
= zipfile.ZipFile('test.zip''w')
z.write('a.log')
z.write('a.data')
z.close()
 
# 解压
= zipfile.ZipFile('test.zip''r')
z.extractall()
z.close()
 
# tarfile模块
import tarfile
 
# 压缩
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
import shelve
   
= shelve.open('shelve_test'#打开一个文件
   
class Test(object):
    def __init__(self,n):
        self.n = n
   
   
= 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模块的练习
"""
 
import xml.etree.ElementTree as ET
 
# 解析xml文件
tree = ET.parse("test.xml")
# 获取根
root = tree.getroot()
print(root.tag)
 
# 遍历xml文档
for child in root:
    print(child.tag, child.attrib)
    for in child:
        print(i.tag, i.text)
 
# 只遍历year节点
for in root.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 练习
"""
 
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)
 
# 读配置文件
config = configparser.ConfigParser()
print(config.sections())
= config.read("test.cfg")
print(a)
print(config.sections())
print("bitbucket.org" in config.sections())
print(config["bitbucket.org"]["user"])
 
for key in config["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
import hashlib
  
= 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进制格式hash
print(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
  
'''
import hashlib
  
# ######## 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正则表达式

开源模块

暂略

原文地址:https://www.cnblogs.com/wangsen-123/p/5806825.html