zoukankan      html  css  js  c++  java
  • Python之常用模块----007

    Python之常用模块

     

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

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

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

    模块分为三种:

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

    1、定义模块

    情景一:

      

    情景二:

      

    情景三:

      

    2、导入模块

    Python之所以应用越来越广泛,在一定程度上也依赖于其为程序员提供了大量的模块以供使用,如果想要使用模块,则需要导入。导入模块有一下几种方法:

    1
    2
    3
    4
    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 文件
    开源模块

    一、下载安装

    下载安装有两种方式:

     方式一
     方式二
    注:在使用源码安装时,需要使用到gcc编译和python开发环境,所以,需要先执行:
    1
    2
    3
    4
    yum install gcc
    yum install python-devel
    apt-get python-dev

    安装成功后,模块会自动安装到 sys.path 中的某个目录中,如:

    1
    /usr/lib/python2.7/site-packages/

    二、导入模块

    同自定义模块中导入的方式

    三、模块 paramiko

    paramiko是一个用于做远程控制的模块,使用该模块可以对远程服务器进行命令或文件操作,值得一说的是,fabric和ansible内部的远程管理就是使用的paramiko来现实。

    1、下载安装

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    # pycrypto,由于 paramiko 模块内部依赖pycrypto,所以先下载安装pycrypto
      
    # 下载安装 pycrypto
    wget http://files.cnblogs.com/files/wupeiqi/pycrypto-2.6.1.tar.gz
    tar -xvf pycrypto-2.6.1.tar.gz
    cd pycrypto-2.6.1
    python setup.py build
    python setup.py install
      
    # 进入python环境,导入Crypto检查是否安装成功
      
    # 下载安装 paramiko
    wget http://files.cnblogs.com/files/wupeiqi/paramiko-1.10.1.tar.gz
    tar -xvf paramiko-1.10.1.tar.gz
    cd paramiko-1.10.1
    python setup.py build
    python setup.py install
      
    # 进入python环境,导入paramiko检查是否安装成功

    2、使用模块

     执行命令 - 通过用户名和密码连接服务器
     执行命令 - 过密钥链接服务器
     上传或者下载文件 - 通过用户名和密码
     上传或下载文件 - 通过密钥
    内置模块

     

    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
    import time
    import datetime
     
    time
    print(time.clock())  #返回处理器时间,3.3以后废弃 4.444098792316153e-07
    print(time.process_time()) #返回处理器时间 0.031200199999999997
    print(time.time())     #返回当前系统时间戳 1463472071.3892002
    print(time.ctime())    #返回当前系统时间 Tue May 17 16:01:11 2016
    print(time.ctime(time.time()-86400))   #转换成字符串格式 Mon May 16 16:01:11 2016
    print(time.gmtime(time.time()-86400))  #将时间戳转换成struct_time格式 time.struct_time(tm_year=2016, tm_mon=5, tm_mday=16, tm_hour=8, tm_min=1, tm_sec=11, tm_wday=0, tm_yday=137, tm_isdst=0)
    print(time.localtime(time.time()-86400))  #将时间戳转换成struct_time格式,本地时间。 time.struct_time(tm_year=2016, tm_mon=5, tm_mday=16, tm_hour=16, tm_min=13, tm_sec=25, tm_wday=0, tm_yday=137, tm_isdst=0)
    print(time.mktime(time.localtime()))  #与time.localtime()功能相反,将struct_time格式转回成时间戳格式  1463472904.0
    time.sleep(4#sleep 每隔四秒以执行
    print(time.strftime("%Y-%m-%d %H:%M:%S",time.gmtime()) ) #将struct_time格式转成指定的字符串格式  2016-05-17 08:16:22
     
    datetime
    print(datetime.date.today()) #输出格式 2016-05-17
    print(datetime.date.fromtimestamp(time.time()-86400) ) # 将时间戳转成日期格式 2016-05-16
    current_time = datetime.datetime.now() #
    print(current_time) #输出2016-05-17 16:17:59.863200
    print(current_time.timetuple()) #返回struct_time格式  time.struct_time(tm_year=2016, tm_mon=5, tm_mday=17, tm_hour=16, tm_min=17, tm_sec=59, tm_wday=1, tm_yday=138, tm_isdst=-1)
     
    #datetime.replace([year[, month[, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]]]])
    print(current_time.replace(2016,5,17)) #输出2016-05-17 16:19:33.753200,返回当前时间,但指定的值将被替换
     
    str_to_date = datetime.datetime.strptime("21/11/06 16:30""%d/%m/%y %H:%M"#将字符串转换成日期格式
    new_date1 = datetime.datetime.now() + datetime.timedelta(days=10#比现在加10天 2016-05-27 16:21:16.279200
    new_date2 = datetime.datetime.now() + datetime.timedelta(days=-10#比现在减10天 2016-05-07 16:21:44.459200
    new_date3 = datetime.datetime.now() + datetime.timedelta(hours=-10#比现在减10小时 2016-05-17 06:22:01.299200
    new_date4 = datetime.datetime.now() + datetime.timedelta(seconds=120#比现在+120s 2016-05-17 16:24:10.917200
    new_date5 = datetime.datetime.now() + datetime.timedelta(weeks=20#比现在+10周 2016-10-04 16:23:02.904200
    print(new_date5)
    DirectiveMeaningNotes
    %a Locale’s abbreviated weekday name.  
    %A Locale’s full weekday name.  
    %b Locale’s abbreviated month name.  
    %B Locale’s full month name.  
    %c Locale’s appropriate date and time representation.  
    %d Day of the month as a decimal number [01,31].  
    %H Hour (24-hour clock) as a decimal number [00,23].  
    %I Hour (12-hour clock) as a decimal number [01,12].  
    %j Day of the year as a decimal number [001,366].  
    %m Month as a decimal number [01,12].  
    %M Minute as a decimal number [00,59].  
    %p Locale’s equivalent of either AM or PM. (1)
    %S Second as a decimal number [00,61]. (2)
    %U Week number of the year (Sunday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Sunday are considered to be in week 0. (3)
    %w Weekday as a decimal number [0(Sunday),6].  
    %W Week number of the year (Monday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Monday are considered to be in week 0. (3)
    %x Locale’s appropriate date representation.  
    %X Locale’s appropriate time representation.  
    %y Year without century as a decimal number [00,99].  
    %Y Year with century as a decimal number.  
    %z Time zone offset indicating a positive or negative time difference from UTC/GMT of the form +HHMM or -HHMM, where H represents decimal hour digits and M represents decimal minute digits [-23:59, +23:59].  
    %Z Time zone name (no characters if no time zone exists).  
    %% A literal '%' character.

    random模块

    随机数

    1
    2
    3
    4
    mport random
    print random.random()
    print random.randint(1,2)
    print random.randrange(1,10)

    生成随机验证码

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    import  random
    tmp = ""
    for in range(6):
        rad1 = random.randrange(4)
        if rad1 ==1 or rad1 ==3:
            rad2 = random.randrange(0,9)
            tmp += str(rad2)
        else:
            rad3 = random.randrange(65,90)
            tmp += chr(rad3)
    print(tmp)

    sys模块

    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
    import sys
    import time
    print(sys.argv)    #['C:/Users/Administrator/PycharmProjects/zyl/day-6/datetime,time模块/SYS.PY.py']
     
    print(sys.path)    #返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
     
    print(exit())   #退出程序,正常退出时exit(0)
     
    print(sys.version)  #3.5.1 (v3.5.1:37a07cee5969, Dec  6 2015, 01:54:25) [MSC v.1900 64 bit (AMD64)]
     
    print(sys.maxsize)   #9223372036854775807  最大的Int值
     
    print(sys.platform)  #win32       操作系统类型
     
     
    ####################################安装包流程不换行显示##################################
    for  in range(31):
        sys.stdout.write(" ")         #清空当前数据网上叠加
        sys.stdout.write("%s%% | %s " %(int(i/30*100),int(i/30*100)*"#"))
        sys.stdout.flush()
        time.sleep(0.3)
     
    ####################################安装流程换行显示####################################
     
    for in range(101):
        sys.stdout.write(" ")
        sys.stdout.write("%s%% | %s " %(i,i*"#"))
        sys.stdout.flush()
        time.sleep(0.1)

     

    json & pickle 模块

    用于序列化的两个模块

    • json,用于字符串 和 python数据类型间进行转换
    • pickle,用于python特有的类型 和 python的数据类型间进行转换

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

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

     pickle 购物实例
     Json实例

    collection系列

    1、计数器(counter)

    Counter是对字典类型的补充,用于追踪值的出现次数。

    ps:具备字典的所有功能 + 自己的功能

    1
    2
    3
    = Counter('abcdeabcdabcaba')
    print c
    输出:Counter({'a'5'b'4'c'3'd'2'e'1})
     collection

    2、有序字典(orderedDict )

    orderdDict是对字典类型的补充,他记住了字典元素添加的顺序

     orderedDict

    3、默认字典(defaultdict) 

    学前需求:

    1
    2
    有如下值集合 [11,22,33,44,55,66,77,88,99,90...],将所有大于 66 的值保存至字典的第一个key中,将小于 66 的值保存至第二个key的值中。
    即: {'k1': 大于66 'k2': 小于66}
     原生字典
     defaultdict解决方法

    defaultdict是对字典的类型的补充,他默认给字典的值设置了一个类型。

     defaultdict

    4、可命名元组(namedtuple) 

    根据nametuple可以创建一个包含tuple所有功能以及其他功能的类型。

    1
    2
    3
    import collections
      
    Mytuple = collections.namedtuple('Mytuple',['x''y''z'])
     Mytuple

    5、双向队列(deque)

    一个线程安全的双向队列

     deque

    注:既然有双向队列,也有单项队列(先进先出 FIFO )

     Queue

    OS模块

    用于提供系统级别的操作:

    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
    os.getcwd()                 获取当前工作目录,即当前python脚本工作的目录路径
    os.chdir("dirname")         改变当前脚本工作目录;相当于shell下cd
    os.curdir                   返回当前目录: ('.')
    os.pardir                   获取当前目录的父目录字符串名:('..')
    os.makedirs('dir1/dir2')    可生成多层递归目录
    os.removedirs('dirname1')   若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推
    os.mkdir('dirname')         生成单级目录;相当于shell中mkdir dirname
    os.rmdir('dirname')         删除单级空目录,若目录不为空则无法删除,报错;相当于shell中rmdir dirname
    os.listdir('dirname')       列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印
    os.remove()                 删除一个文件
    os.rename("oldname","new")  重命名文件/目录
    os.stat('path/filename')    获取文件/目录信息
    os.sep                      操作系统特定的路径分隔符,win下为"\",Linux下为"/"
    os.linesep                  当前平台使用的行终止符,win下为" ",Linux下为" "
    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所指向的文件或者目录的最后修改时间

      

    hashlib

    用于加密相关的操作,代替了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
    import hashlib
      
    # ######## md5 ########
    hash = hashlib.md5()
    # help(hash.update)
    hash.update(bytes('admin', encoding='utf-8'))
    print(hash.hexdigest())
    print(hash.digest())
      
      
    ######## sha1 ########
      
    hash = hashlib.sha1()
    hash.update(bytes('admin', encoding='utf-8'))
    print(hash.hexdigest())
      
    # ######## sha256 ########
      
    hash = hashlib.sha256()
    hash.update(bytes('admin', encoding='utf-8'))
    print(hash.hexdigest())
      
      
    # ######## sha384 ########
      
    hash = hashlib.sha384()
    hash.update(bytes('admin', encoding='utf-8'))
    print(hash.hexdigest())
      
    # ######## sha512 ########
      
    hash = hashlib.sha512()
    hash.update(bytes('admin', encoding='utf-8'))
    print(hash.hexdigest())

    以上加密算法虽然依然非常厉害,但时候存在缺陷,即:通过撞库可以反解。所以,有必要对加密算法中添加自定义key再来做加密。

    1
    2
    3
    4
    5
    6
    7
    import hashlib
      
    # ######## md5 ########
      
    hash = hashlib.md5(bytes('898oaFs09f',encoding="utf-8"))
    hash.update(bytes('admin',encoding="utf-8"))
    print(hash.hexdigest())

    python内置还有一个 hmac 模块,它内部对我们创建 key 和 内容 进行进一步的处理然后再加密

    1
    2
    3
    4
    5
    import hmac
      
    = hmac.new(bytes('898oaFs09f',encoding="utf-8"))
    h.update(bytes('admin',encoding="utf-8"))
    print(h.hexdigest())
     实例

    XML

    XML是实现不同语言或程序之间进行数据交换的协议,XML文件格式如下:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    <data>
        <country name="Liechtenstein">
            <rank updated="yes">2</rank>
            <year>2023</year>
            <gdppc>141100</gdppc>
            <neighbor direction="E" name="Austria" />
            <neighbor direction="W" name="Switzerland" />
        </country>
        <country name="Singapore">
            <rank updated="yes">5</rank>
            <year>2026</year>
            <gdppc>59900</gdppc>
            <neighbor direction="N" name="Malaysia" />
        </country>
        <country name="Panama">
            <rank updated="yes">69</rank>
            <year>2026</year>
            <gdppc>13600</gdppc>
            <neighbor direction="W" name="Costa Rica" />
            <neighbor direction="E" name="Colombia" />
        </country>
    </data>

    1、解析XML

     利用ElementTree.XML将字符串解析成xml对象
     利用ElementTree.parse将文件直接解析成xml对象

    2、操作XML

    XML格式类型是节点嵌套节点,对于每一个节点均有以下功能,以便对当前节点进行操作:

     节点功能一览表

    由于 每个节点 都具有以上的方法,并且在上一步骤中解析时均得到了root(xml文件的根节点),so   可以利用以上方法进行操作xml文件。

    a. 遍历XML文档的所有内容

     a

    b、遍历XML中指定的节点

     b

    c、修改节点内容

    由于修改的节点时,均是在内存中进行,其不会影响文件中的内容。所以,如果想要修改,则需要重新将内存中的内容写到文件。

     解析字符串方式,修改,保存
     解析文件方式,修改,保存

    d、删除节点

     解析字符串方式打开,删除,保存
     解析文件方式打开,删除,保存

    3、创建XML文档

     
     
     

    由于原生保存的XML时默认无缩进,如果想要设置缩进的话, 需要修改保存方式:

     缩进

    4、命名空间

     命名

    requests

    Python标准库中提供了:urllib等模块以供Http请求,但是,它的 API 太渣了。它是为另一个时代、另一个互联网所创建的。它需要巨量的工作,甚至包括各种方法覆盖,来完成最简单的任务。

     发送GET请求
     发送携带请求头的GET请求

    Requests 是使用 Apache2 Licensed 许可证的 基于Python开发的HTTP 库,其在Python内置模块的基础上进行了高度的封装,从而使得Pythoner进行网络请求时,变得美好了许多,使用Requests可以轻而易举的完成浏览器可有的任何操作。

    1、安装模块

    1
    pip3 install requests

    2、使用模块

     GET请求
     POST请求
     其他请求

    3、Http请求和XML实例

    实例:检测QQ账号是否在线

     QQ

    实例:查看火车停靠信息

     火车票

    综合应用实例

    1、通过HTTP请求和XML实现获取电视节目

         API:http://www.webxml.com.cn/webservices/ChinaTVprogramWebService.asmx  

     电视节目

    2、通过HTTP请求和JSON实现获取天气状况

         API:http://wthrcdn.etouch.cn/weather_mini?city=北京

     天气预报

    configparser

    configparser模块用于读取基于Windows INI格式的.ini格式的配置文件。这些文件由命名段祖闯,每个命名段独有自己的变量赋值,格式如下:

     格式

    configparser模块往往被忽视,但他是一个及其有用的工具,它可以控制包含极其复杂的用户配置或运行时环境的程序,例如:若编写了必须在大兴框架内运行的组件,那么配置文件往往是提供运行时参数的理想方式

    1、获取所有节点

    1
    2
    3
    4
    5
    6
    import configparser
      
    config = configparser.ConfigParser()
    config.read('xxxooo', encoding='utf-8')
    ret = config.sections()   #获取大节点
    print(ret)

    2、获取指定节点下所有的键值对

    1
    2
    3
    4
    5
    6
    import configparser
      
    config = configparser.ConfigParser()
    config.read('xxxooo', encoding='utf-8')
    ret = config.items('section1'#键值对
    print(ret) 

    3、获取指定节点下所有的键

    1
    2
    3
    4
    5
    6
    import configparser
      
    config = configparser.ConfigParser()
    config.read('xxxooo', encoding='utf-8')
    ret = config.options('section1')   #二级节点
    print(ret)

    4、获取指定节点下指定key的值

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    import configparser
      
    config = configparser.ConfigParser()
    config.read('xxxooo', encoding='utf-8')
      
      
    = config.get('section1''k1'#获取值的值
    # v = config.getint('section1', 'k1')  #整形
    # v = config.getfloat('section1', 'k1')   #浮点
    # v = config.getboolean('section1', 'k1')   #布尔

    5、检查、删除、添加节点

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    import configparser
      
    config = configparser.ConfigParser()
    config.read('xxxooo', encoding='utf-8')
      
      
    # 检查
    has_sec = config.has_section('section1')
    print(has_sec)
      
    # 添加节点
    config.add_section("SEC_1")
    config.write(open('xxxooo''w'))
      
    # 删除节点
    config.remove_section("SEC_1")
    config.write(open('xxxooo''w'))

    6、检查、删除、设置指定组内的键值对

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    import configparser
      
    config = configparser.ConfigParser()
    config.read('xxxooo', encoding='utf-8')
      
    # 检查
    has_opt = config.has_option('section1''k1')
    print(has_opt)
      
    # 删除
    config.remove_option('section1''k1')
    config.write(open('xxxooo''w'))
      
    # 设置
    config.set('section1''k10'"123")
    config.write(open('xxxooo''w'))

    系统命令subprocess

    subprocess模块包含的函数和对象用于简化创建新进程的任务、控制输入和输出流,以及处理返回代码。此模块的猪獒功能包含在其他各个模块中,如os、popen、commands

    格式

    以上执行shell命令的相关的模块和函数的功能均在 subprocess 模块中实现,并提供了更丰富的功能。

    popen(args,**parms)

    以子进程形式执行一个新命令,然后返回代表新进程的popen对象,命令在args中指定,是字符串(如 “ls -l”)。parms表示关键字参数的集合,设置这些参数可以控制子进程的各种属性

    参数:

      • 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 -> 同意使用
      • startupinfo与createionflags只在windows下有效
        将被传递给底层的CreateProcess()函数,用于设置子进程的一些属性,如:主窗口的外观,进程的优先级等等 
     普通命令

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

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

    call(args,**parms)

    此函数与popen完全相同,但他指挥简单的执行命令然后返回他的状态代码。如果要执行一个命令,单又不需要捕捉他的输出,可以使用这个函数

    执行命令,返回状态码

    1
    2
    ret = subprocess.call(["ls""-l"], shell=False)
    ret = subprocess.call("ls -l", shell=True)

    check_call(args,**parms)

    同call函数,但如果退出代码为非0值,将引发异常,此异常将退出代码保存在他的returncode属性中。

    执行命令,如果执行状态码是 0 ,则返回0,否则抛异常

    1
    2
    subprocess.check_call(["ls""-l"])
    subprocess.check_call("exit 1", shell=True)

    check_output(args,**parms)

    执行命令,如果状态码是 0 ,则返回执行结果,否则抛异常

    subprocess.check_output(["echo", "Hello World!"])
    subprocess.check_output("exit 1", shell=True)

    shutil

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

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

    1
    2
    3
    import shutil
      
    shutil.copyfileobj(open('old.xml','r'), open('new.xml''w'))

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

    1
    shutil.copyfile('f1.log''f2.log')

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

    1
    shutil.copymode('f1.log''f2.log')

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

    1
    shutil.copystat('f1.log''f2.log')

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

    1
    2
    3
    import shutil
      
    shutil.copy('f1.log''f2.log')

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

    1
    2
    3
    import shutil
      
    shutil.copy2('f1.log''f2.log')

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

    1
    2
    3
    import shutil
      
    shutil.copytree('folder1''folder2', ignore=shutil.ignore_patterns('*.pyc''tmp*'))
     View Code

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

    1
    2
    3
    import shutil
      
    shutil.rmtree('folder1')

    shutil.move(src, dst)
    递归的去移动文件,它类似mv命令,其实就是重命名。

    1
    2
    3
    import shutil
      
    shutil.move('folder1''folder3')

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

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

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

      • base_name: 压缩包的文件名,也可以是压缩包的路径。只是文件名时,则保存至当前目录,否则保存至指定路径,
        如:www                        =>保存至当前路径
        如:/Users/wupeiqi/www =>保存至/Users/wupeiqi/
      • format: 压缩包种类,“zip”, “tar”, “bztar”,“gztar”
      • root_dir: 要压缩的文件夹路径(默认当前目录)
      • owner: 用户,默认当前用户
      • group: 组,默认当前组
      • logger: 用于记录日志,通常是logging.Logger对象
    1
    2
    3
    4
    5
    6
    7
    8
    #将 /Users/wupeiqi/Downloads/test 下的文件打包放置当前程序目录
    import shutil
    ret = shutil.make_archive("wwwwwwwwww"'gztar', root_dir='/Users/wupeiqi/Downloads/test')
       
       
    #将 /Users/wupeiqi/Downloads/test 下的文件打包放置 /Users/wupeiqi/目录
    import shutil
    ret = shutil.make_archive("/Users/wupeiqi/wwwwwwwwww"'gztar', root_dir='/Users/wupeiqi/Downloads/test')

    shutil 对压缩包的处理是调用 ZipFile 和 TarFile 两个模块来进行的,详细:

     zip解压
     tar解压
    学习记录,小白一枚
  • 相关阅读:
    linux ps查看进程命令
    linux distribution是什么?
    samba配置smb.conf
    linux samba.tar.gz安装和配置
    linux后台执行命令&
    linux crontab任务调度的使用
    linux ubuntu卸载软件
    vue-router
    vue computed
    vue 监听的使用
  • 原文地址:https://www.cnblogs.com/wangsirde0428/p/13341291.html
Copyright © 2011-2022 走看看