Python学习之路——模块

一、模块:

模块,用一砣代码实现了某个功能的代码集合。 

类似于函数式编程和面向过程编程,函数式编程则完成一个功能,其他代码用来调用即可,提供了代码的重用性和代码间的耦合。而对于一个复杂的功能来,可能需要多个函数才能完成(函数又可以在不同的.py文件中),n个 .py 文件组成的代码集合就称为模块。

如:os 是系统相关的模块;file是文件操作相关的模块

模块分为三种:

  • 自定义模块
  • 内置模块
  • 开源模块

二、导入模块:

import module
from module.xx.xx import xx
from module.xx.xx import xx as rename  
from module.xx.xx import *   # 此方法不建议使用。
导入模块方式

导入模块其实就是告诉Python解释器去解释那个py文件

  • 导入一个py文件,解释器解释该py文件
  • 导入一个包,解释器解释该包下的 __init__.py 文件

导入模块路径的基准路径需要使用sys.path来查看,如下:

import sys
print(sys.path)
以上实例Linux输出结果:
['', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-linux2', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/usr/lib/pymodules/python2.7']

以上实例Windows输出结果:
['E:\\project\\s12\\day5', 'E:\\project\\s12', 'E:\\project\\stu104381', 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python35\\python35.zip', 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python35\\DLLs', 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python35\\lib', 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python35', 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python35\\lib\\site-packages']

添加模块路径:

import sys
import os
pre_path = os.path.abspath('../')
sys.path.append(pre_path)
添加模块路径

注:sys.path就是一个列表只要把要添加的路径append到里面就可以了。

三、time与datetime模块:

print(time.clock()) #返回处理器时间
以上实例输出结果:
7.07798237865507e-07

print(time.process_time()) #返回处理器时间
以上实例输出结果:
0.046800299999999996

print(time.time()) #返回当前系统时间戳
以上实例输出结果:
1454318920.473497

print(time.ctime()) #输出当前系统时间
以上实例输出结果:
Mon Feb  1 17:30:02 2016

print(time.ctime(time.time()-86640)) #取昨天时间。
以上实例输出结果:
Sun Jan 31 17:26:54 2016

print(time.gmtime(time.time())) #取当前时间的struct_time格式
以上实例输出结果:
time.struct_time(tm_year=2016, tm_mon=2, tm_mday=1, tm_hour=9, tm_min=33, tm_sec=49, tm_wday=0, tm_yday=32, tm_isdst=0)


print(time.localtime(time.time())) #以struct_time格式,但返回本地时间
以上实例输出结果:
time.struct_time(tm_year=2016, tm_mon=2, tm_mday=1, tm_hour=17, tm_min=37, tm_sec=56, tm_wday=0, tm_yday=32, tm_isdst=0)
注:gmtime与localtime区别在于,gmtime反回的是格林威治时间,而localtime返回的是北京时间。

print(time.mktime(time.localtime())) #与time.localtime()功能相反,将struct_time格式转回成时间戳格式
以上实例输出结果:
1454319614.0

time.sleep(4) #休眠4秒

print(time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()) ) #将struct_time格式转成指定的字符串格式
以上实例输出结果:
2016-02-01 17:43:34

print(time.strptime("2016-02-01","%Y-%m-%d") ) #将字符串格式转换成struct_time格式
以上实例输出结果:
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)
time模块
print(datetime.date.today()) #输出格式%Y-%m-%d格式输出
以上实例输出结果:
2016-02-01

print(datetime.date.fromtimestamp(time.time()) ) #2016-01-16 将时间戳转成日期格式
以上实例输出结果:
2016-02-01

print(datetime.datetime.now())#输出日期带毫秒级别
以上实例输出结果:
2016-02-01 17:51:46.091749

current_time = datetime.datetime.now()
print(current_time.timetuple()) #返回struct_time格式
以上实例输出结果:
time.struct_time(tm_year=2016, tm_mon=2, tm_mday=1, tm_hour=17, tm_min=54, tm_sec=11, tm_wday=0, tm_yday=32, tm_isdst=-1)


current_time = datetime.datetime.now()
print(current_time.replace(2013,6,12)) #返回当前时间,但指定的值将被替换
以上实例输出结果:
2013-06-12 17:56:01.377351

print(datetime.datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M")) #将字符串转换成日期格式
以上实例输出结果:
2006-11-21 16:30:00

 print(datetime.datetime.now() + datetime.timedelta(days=10)) #比现在加10天
以上实例输出结果:
2016-02-11 17:59:18.593631

print(datetime.datetime.now() + datetime.timedelta(days=-10)) #比现在减10天
以上实例输出结果:
2016-01-22 18:00:29.296675

print(datetime.datetime.now() + datetime.timedelta(hours=-10)) #比现在减10小时
以上实例输出结果:
2016-02-01 08:00:58.682356

print(datetime.datetime.now() + datetime.timedelta(seconds=120)) #比现在+120s
以上实例输出结果:
2016-02-01 18:03:45.592039
datetime模块

四、random模块

random模块是用来生成随即数的:

import random
print(random.random())     #随机值。
以上实例输出结果:
0.7037924498861795

print(random.randint(1, 2))  #在1与2之间随机输出一个值。
以上实例输出结果:
2

print(random.randrange(1, 10)) #在1与10之间随机输出一个值。
以上实例输出结果:
9
random模块:

 

使用random模块生成验证码:

import random
checkcode = ''
for i in range(4):
    current = random.randrange(0,4)
    if current != i:
        temp = chr(random.randint(65,90))
    else:
        temp = random.randint(0,9)
    checkcode += str(temp)
print(checkcode)

以上实例输出结果:
E59J
验证码实例:

五、OS模块:

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所指向的文件或者目录的最后修改时间
OS模块:

六、sys模块

sys.argv           命令行参数List,第一个元素是程序本身路径
sys.exit(n)        退出程序,正常退出时exit(0)
sys.version        获取Python解释程序的版本信息
sys.maxint         最大的Int值
sys.path           返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
sys.platform       返回操作系统平台名称
sys模块:
import sys,time
for i in range(10):
    sys.stdout.write("#")
    sys.stdout.flush()
    time.sleep(0.3)
进度条实例:

七、用于序列化的模块json和pickle

Json:可将序列化的数据在任何语言之前进行传递。

picke:只能将序列化的数据在python之前传递,但是picke可以将大部分数据类型进行序列化,例如说函数等。

Json模块提供了四个功能:dumps、dump、loads、load

pickle模块提供了四个功能:dumps、dump、loads、load

 

八、xml处理模块:

xml是实现不同语言或程序之间进行数据交换的协议,跟json差不多,但json使用起来更简单,xml是在没有json之前出现的序列化模块,为在太老,所以只有银行等一些程序在使用。

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>
xml的格式

xml协议在各个语言里的都 是支持的,在python中可以用以下模块操作xml

import xml.etree.ElementTree as ET

tree = ET.parse("xml_test.xml")
root = tree.getroot()
# print(root.tag)

#遍历xml文档
for child in root:
    print(child.tag, child.attrib)
    for i in child:
        print(i.text)


#只遍历year 节点
for node in root.iter('year'):
    print(node.tag,node.text)
xml遍历
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.text = str(new_year)
    node.set("updated","yes")
 
tree.write("xmltest.xml")
 
 
xml修改
#删除node
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) #打印生成的格式
xml创建

 

九、configparser模块:

 

1.基本的读取配置文件

-read(filename) 直接读取ini文件内容

-sections() 得到所有的section,并以列表的形式返回

-options(section) 得到该section的所有option

-items(section) 得到该section的所有键值对

-get(section,option) 得到section中option的值,返回为string类型

-getint(section,option) 得到section中option的值,返回为int类型,还有相应的getboolean()和getfloat() 函数。

2.基本的操作配置文件

-add_section(section) 添加一个新的section

-set( section, option, value) 对section中的option进行设置,需要调用write将内容写入配置文件。

-config.has_section(section) 判断section是否存在,存在返回True ,不存在返回False。

-config.has_option(section,option) 判断option是否存在,存在返回True ,不存在返回False。

-config.remove_section(section) 删除section。

-config.remove_option(section,option) 删除option。

 

示例文件:

[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes

[bitbucket.org]
User = hg

[topsecret.server.com]
Port = 50022
ForwardX11 = no
configparser示例:
取conf_test.ini文件下ServerAliveInterval的值:
import configparser
config = configparser.ConfigParser()
config.read('conf_test.ini')
x = config['DEFAULT']['ServerAliveInterval']
print(x)

以上实例输出结果:
45
取值配置子元素值:
import configparser
config = configparser.ConfigParser()
config.read('conf_test.ini')

secs = config.defaults()
print(secs)

以上实例输出结果:
OrderedDict([('serveraliveinterval', '45'), ('compression', 'yes'), ('compressionlevel', '9'), ('forwardx11', 'yes')])
取DEFAULT信息:
import configparser
config = configparser.ConfigParser()
config.read('conf_test.ini')

secs = config.sections()
print(secs)
以上实例输出结果:
['bitbucket.org', 'topsecret.server.com']

注:在python3.x版本是不会输出[DEFAULT]的sections。
sections函数:
import configparser
config = configparser.ConfigParser()
config.read('conf_test.ini')


opt = config.options('bitbucket.org')
print(opt)
以上实例输出结果:
['user', 'serveraliveinterval', 'compression', 'compressionlevel', 'forwardx11']

注:在打印子sections时都会将default的option打引出来。
options函数:
import configparser
config = configparser.ConfigParser()
config.read('conf_test.ini')

# secs = config.sections()
print(config.items('DEFAULT'))
opt = config.items('bitbucket.org')
print(opt)

以上实例输出结果:
[('serveraliveinterval', '45'), ('compression', 'yes'), ('compressionlevel', '9'), ('forwardx11', 'yes')]
[('serveraliveinterval', '45'), ('compression', 'yes'), ('compressionlevel', '9'), ('forwardx11', 'yes'), ('user', 'hg')]
items函数:
import configparser
config = configparser.ConfigParser()
config.read('conf_test.ini')

x = config.get('bitbucket.org','User')
print(x)
以上实例输出结果:
hg
get函数:
import configparser
config = configparser.ConfigParser()
config.read('conf_test.ini')

x = config.add_section('bin')
config.write(open('conf_test_new.ini','w'))

输出结果是生成一个conf_test_new.ini文件,内容:
[DEFAULT]
serveraliveinterval = 45
compression = yes
compressionlevel = 9
forwardx11 = yes

[bitbucket.org]
user = hg

[topsecret.server.com]
port = 50022
forwardx11 = no

[bin]
add_section函数
import configparser
config = configparser.ConfigParser()
config.read('conf_test.ini')

config.add_section('song')
config.set('song','age','20')
config.write(open('conf_test_new.ini','w'))

conf_test_new.ini文件变成如下:
[DEFAULT]
serveraliveinterval = 45
compression = yes
compressionlevel = 9
forwardx11 = yes

[bitbucket.org]
user = hg

[topsecret.server.com]
port = 50022
forwardx11 = no

[song]
age = 20

注:在添加song下的age项时,song一定要存在,否则程序会报错。
set函数
has_section函数:判断section是否存在:
import configparser
config = configparser.ConfigParser()
config.read('conf_test.ini')

x = config.has_section('bitbucket.org')
print(x)
y = config.has_section('test')
print(y)

以上实例输出结果:
True
False
has_section函数:
remove_section函数:删除section项:

import configparser
config = configparser.ConfigParser()
config.read('conf_test.ini')

config.remove_section('bitbucket.org')
config.write(open('conf_test_new.ini','w'))

conf_test_new.ini文件变成如下:
[DEFAULT]
serveraliveinterval = 45
compression = yes
compressionlevel = 9
forwardx11 = yes

[topsecret.server.com]
port = 50022
forwardx11 = no

注:里面缺少了bitbucket.org项。
remove_section函数:
remove_option函数:删除option选项:

import configparser
config = configparser.ConfigParser()
config.read('conf_test.ini')

config.remove_option('bitbucket.org','User')
config.write(open('conf_test_new.ini','w'))

conf_test_new.ini文件变成如下:

[DEFAULT]
serveraliveinterval = 45
compression = yes
compressionlevel = 9
forwardx11 = yes

[bitbucket.org]

[topsecret.server.com]
port = 50022
forwardx11 = no

注:bitbucket.org下少了User = hg。
remove_option函数:

 

十、hashlib模块:

用于加密相关的操作,3.x里代替了md5模块和sha模块,主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 算法:

import hashlib

m = hashlib.md5()
m.update(b"Hello")
print(m.hexdigest())

以上实例输出结果:
8b1a9953c4611296a827abf8c47804d7
md5示例:
import hashlib

m = hashlib.sha1()
m.update(b'Hello')
print(m.hexdigest())
以上实例输出结果:
f7ff9e8b7bb2e09b70935a5d785e0cc5d9d0abf0
sha1示例:
import hashlib

m = hashlib.sha224()
m.update(b'Hello')
print(m.hexdigest())
以上实例输出结果:
4149da18aa8bfc2b1e382c6c26556d01a92c261b6436dad5e3be3fcc
sha224示例
import hashlib

m = hashlib.sha256()
m.update(b'Hello')
print(m.hexdigest())
以上实例输出结果:
185f8db32271fe25f561a6fc938b2e264306ec304eda518007d1764826381969
sha256示例
import hashlib

m = hashlib.sha384()
m.update(b'Hello')
print(m.hexdigest())
以上实例输出结果:
3519fe5ad2c596efe3e276a6f351b8fc0b03db861782490d45f7598ebd0ab5fd5520ed102f38c4a5ec834e98668035fc
sha384示例
import hashlib

m = hashlib.sha512()
m.update(b'Hello')
print(m.hexdigest())
以上实例输出结果:
3615f80c9d293ed7402687f94b22d58e529b8cc7916f8fac7fddf7fbd5af4cf777d3d795a7a00a16bf7e7f3fb9561ee9baae480da9fe7a18769e71886b03f315
sha512示例

 

十一、hmac模块:

它内部对我们创建 key 和 内容 再进行处理然后再加密:

import hmac
h = hmac.new(b'k1')
h.update(b'hello')
print(h.hexdigest())
以上实例输出结果:
6edfd80014764676e8c9399fd3a934e1
hmac示例

 

十二、subprocess模块:

>>> subprocess.run('ls -l',shell=True)
总用量 12
drwx------ 6 apache apache 4096 12月 29 18:53 apache
drwx------ 4 sjb    sjb    4096 12月 22 12:36 sjb
drwx------ 4 svn    svn    4096 12月 22 13:38 svn
CompletedProcess(args='ls -l', returncode=0)
run函数
>>> subprocess.check_output(["echo", "Hello World!"])
b'Hello World!\n'
>>> subprocess.check_output('sfsfs')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.5/subprocess.py", line 629, in check_output
    **kwargs).stdout
  File "/usr/local/lib/python3.5/subprocess.py", line 696, in run
    with Popen(*popenargs, **kwargs) as process:
  File "/usr/local/lib/python3.5/subprocess.py", line 950, in __init__
    restore_signals, start_new_session)
  File "/usr/local/lib/python3.5/subprocess.py", line 1544, in _execute_child
    raise child_exception_type(errno_num, err_msg)
FileNotFoundError: [Errno 2] No such file or directory: 'sfsfs'
check_output

注:check_output执行成功返回执行结果,如果失败则报错。

>>> import subprocess
>>> subprocess.call(["ls", "-l"], shell=False)
总用量 965988
drwxr-xr-x 2 yx yx      4096  1月  7 02:31 2016-01-07
drwxr-xr-x 8 yx yx      4096  1月 12 11:33 jdk1.6.0_38
-rwxr-xr-x 1 yx yx  72056550  1月 12 11:33 jdk-6u38-ea-bin-b04-linux-amd64-31_oct_2012.bin
-rw-r--r-- 1 yx yx 917100288  1月 12 14:55 solr_home.tar.gz
0
>>> subprocess.call("ls -l", shell=True)
总用量 965988
drwxr-xr-x 2 yx yx      4096  1月  7 02:31 2016-01-07
drwxr-xr-x 8 yx yx      4096  1月 12 11:33 jdk1.6.0_38
-rwxr-xr-x 1 yx yx  72056550  1月 12 11:33 jdk-6u38-ea-bin-b04-linux-amd64-31_oct_2012.bin
-rw-r--r-- 1 yx yx 917100288  1月 12 14:55 solr_home.tar.gz
0
subprocess

调用subprocess.run(...)是推荐的常用方法,在大多数情况下能满足需求,但如果你可能需要进行一些复杂的与系统的交互的话,你还可以用subprocess.Popen(),语法如下:

p = subprocess.Popen("find / -size +1000000 -exec ls -shl {} \;",shell=True,stdout=subprocess.PIPE)
print(p.stdout.read())
Popen

用于执行复杂的系统命令

参数:

    • args:shell命令,可以是字符串或者序列类型(如:list,元组)
    • bufsize:指定缓冲。0 无缓冲,1 行缓冲,其他 缓冲区大小,负值 系统缓冲
    • stdin, stdout, stderr:分别表示程序的标准输入、输出、错误句柄
    • preexec_fn:只在Unix平台下有效,用于指定一个可执行对象(callable object),它将在子进程运行之前被调用
    • close_sfs:在windows平台下,如果close_fds被设置为True,则新创建的子进程将不会继承父进程的输入、输出、错误管道。
      所以不能将close_fds设置为True同时重定向子进程的标准输入、输出与错误(stdin, stdout, stderr)。
    • shell:同上
    • cwd:用于设置子进程的当前目录
    • env:用于指定子进程的环境变量。如果env = None,子进程的环境变量将从父进程中继承。
    • universal_newlines:不同系统的换行符不同,True -> 同意使用 \n
    • startupinfo与createionflags只在windows下有效
      将被传递给底层的CreateProcess()函数,用于设置子进程的一些属性,如:主窗口的外观,进程的优先级等等
import subprocess
ret1 = subprocess.Popen(["mkdir","t1"])
ret2 = subprocess.Popen("mkdir t2", shell=True)
执行普通命令:

终端输入的命令分为两种:

  • 输入即可得到输出,如:ifconfig
  • 输入进行某环境,依赖再输入,如:python
import subprocess

obj = subprocess.Popen("mkdir t3", shell=True, cwd='/home/dev',)
View Code

 

import subprocess

obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
obj.stdin.write('print 1 \n ')
obj.stdin.write('print 2 \n ')
obj.stdin.write('print 3 \n ')
obj.stdin.write('print 4 \n ')
obj.stdin.close()

cmd_out = obj.stdout.read()
obj.stdout.close()
cmd_error = obj.stderr.read()
obj.stderr.close()

print cmd_out
print cmd_error
View Code

 

import subprocess

obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
obj.stdin.write('print 1 \n ')
obj.stdin.write('print 2 \n ')
obj.stdin.write('print 3 \n ')
obj.stdin.write('print 4 \n ')

out_error_list = obj.communicate()
print out_error_list
View Code

 

import subprocess

obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out_error_list = obj.communicate('print "hello"')
print out_error_list
View Code

注:在执行命令时如果在后面加上shell=True是让程序使用系统自身的shell,如果不加此参数或shell=Flas是使用解释器转换。

 

十三、shutil

 

高级的 文件、文件夹、压缩包 处理模块

shutil.copyfileobj(fsrc, fdst[, length])
将文件内容拷贝到另一个文件中,可以部分内容

shutil.copyfile(src, dst)
拷贝文件

shutil.copymode(src, dst)
仅拷贝权限。内容、组、用户均不变

shutil.copystat(src, dst)
拷贝状态的信息,包括:mode bits, atime, mtime, flags

shutil.copy(src, dst)
拷贝文件和权限

shutil.copy2(src, dst)
拷贝文件和状态信息

shutil.ignore_patterns(*patterns)
shutil.copytree(src, dst, symlinks=False, ignore=None)
递归的去拷贝文件

例如:copytree(source, destination, ignore=ignore_patterns('*.pyc', 'tmp*'))

shutil.rmtree(path[, ignore_errors[, onerror]])
递归的去删除文件

shutil.move(src, dst)
递归的去移动文件

 

shutil.make_archive(base_name, format,...)

创建压缩包并返回文件路径,例如:zip、tar

    • base_name: 压缩包的文件名,也可以是压缩包的路径。只是文件名时,则保存至当前目录,否则保存至指定路径,
      如:www                        =>保存至当前路径
      如:/Users/wupeiqi/www =>保存至/Users/wupeiqi/
    • format: 压缩包种类,“zip”, “tar”, “bztar”,“gztar”
    • root_dir: 要压缩的文件夹路径(默认当前目录)
    • owner: 用户,默认当前用户
    • group: 组,默认当前组
    • logger: 用于记录日志,通常是logging.Logger对象

 

#将 /Users/test/Downloads/test 下的文件打包放置当前程序目录
 
import shutil
ret = shutil.make_archive("wwwwwwwwww", 'gztar', root_dir='/Users/test/Downloads/test')
 
 
#将 /Users/test/Downloads/test 下的文件打包放置 /Users/test/目录
import shutil
ret = shutil.make_archive("/Users/test/wwwwwwwwww", 'gztar', root_dir='/Users/test/Downloads/test')
make_archive函数

 

十四、ZipFile模块

import zipfile

# 压缩
z = zipfile.ZipFile('test.zip', 'w')
z.write('a.log')
z.write('data.data')
z.close()

# 解压
z = zipfile.ZipFile('test.zip', 'r')
z.extractall()
z.close()
ZipFile示例

 

十五、tarfile模块:

import tarfile

# 压缩
tar = tarfile.open('your.tar','w')
tar.add('/Users/test/PycharmProjects/bbs2.zip', arcname='bbs2.zip')
tar.add('/Users/test/PycharmProjects/cmdb.zip', arcname='cmdb.zip')
tar.close()

# 解压
tar = tarfile.open('your.tar','r')
tar.extractall()  # 可设置解压地址
tar.close()
tarfile示例

 

十六、logging模块:

用于记录程序操作相关的日志模块。

import logging
 
logging.warning("user [test] attempted wrong password more than 3 times")
logging.critical("server is down")

以上实例输出结果:
WARNING:root:user [test] attempted wrong password more than 3 times
CRITICAL:root:server is down

  

日志等级:

CRITICAL = 50
FATAL = CRITICAL
ERROR = 40
WARNING = 30
WARN = WARNING
INFO = 20
DEBUG = 10
NOTSET = 0
日志等级

对于格式,有如下属性可是配置:

 

import logging
 
#create logger
logger = logging.getLogger('TEST-LOG')
logger.setLevel(logging.DEBUG)
 
 
# create console handler and set level to debug
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
 
# create file handler and set level to warning
fh = logging.FileHandler("access.log")
fh.setLevel(logging.WARNING)
# create formatter
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
 
# add formatter to ch and fh
ch.setFormatter(formatter)
fh.setFormatter(formatter)
 
# add ch and fh to logger
logger.addHandler(ch)
logger.addHandler(fh)
 
# 'application' code
logger.debug('debug message')
logger.info('info message')
logger.warn('warn message')
logger.error('error message')
logger.critical('critical message')
日志示例:

 

posted @ 2016-02-01 18:32  Earl.宋  阅读(224)  评论(0编辑  收藏  举报