zoukankan      html  css  js  c++  java
  • python 之常用模块

    模块(module):

    模块实质是一个python文件,也就是把python代码写到模块里面。

    模块分类:

    标准库:python内置

    开源模块:第三方

    自定义模块:自己写

    一、os , sys 模块

    import os, sys
    
    print(os.getcwd())     #获取当前目录
    
    os.chmod("/usr/share", 7)   #给/usr/share目录添加权限
    
    print(os.curdir)  #当前目录
    
    print(os.pardir)  #父目录
    
    print(os.makedirs("/usr/local/mysql"))   #递归创建目录,父目录不存在时创建目录
    
    print(os.removedirs("/usr/local/mysql"))  #递归删除空目录
    
    print(os.mkdir("new"))  #创建文件夹
    
    os.rename("old", "new")  #重命名
    
    print(os.path.join("/root",'mysql','rack.sql')) #拼接成一个路径
    
    print(os.path.split("/usr/mysql/123.txt"))     #分割路径和文件名
    
    print(os.sep)        #当前操作系统的路径分隔符
    
    print(os.linesep)    #当前操作系统的换行符
    
    print(os.pathsep)  #当前系统的环境变量中每个路径的分隔符,linux是:,windows是;
      
    print(os.environ)  #当前系统的环境变量
    
    print(os.path.abspath(__file__))   #获取绝对路径
    
    print(sys.version)    #获取系统版本
    
    print(sys.argv)        #命令行参数List,第一个元素是程序本身路径
    
    print(sys.path)        #返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
    
    print(sys.platform)  #返回操作系统名称
    
    sys.stdout.write('please:')   #向屏幕输出一句话
    
    print(sys.maxsize)   #最大值

    二、random, string模块

    import random, string
    
    print(random.random())  #随机取浮点数,默认是0~1,不能指定取值范围
    
    print(random.randint(1,18))  #随机取整数
    
    print(random.randrange(1,28))   #随机产生一个range
    
    print(random.choice('sjdkf93f')   #随机选择一个元素
    
    print(random.sample('hello', 3))  #随机取3个元素
    
    print(random.uniform(1, 9))     #随机取浮点数,可以指定取值范围
    
    f = [1, 2, 3, 4, 5]
    
    random.shuffle(f)   #打乱顺序
    
    print(f)
    
    print(string.ascii_letters+string.digits)       #所有的数字和字母

    三、time&timedate模块

    时间有三种表示方式,一种是时间戳、一种是格式化时间、一种是时间元组

    import time, timedate
    
    print(time.timezone())    #和标准时间相差的时间,单位是s
    
    print(time.time())    #获取当前的时间戳
    
    print(time.sleep(1))   #休息1s
    
    print(time.gmtime())#把时间戳转换成时间元组,如果不传的话,默认取标准时区的时间戳
    
    print(time.localtime())#把时间戳转换成时间元组,如果不传的话,默认取当前时区的时间戳

    print(time.mktime(time.localtime())) #把时间元组转换成时间戳 print(time.strftime("%y%n%d %H%M%S")) #将时间元组转换成格式化输出的字符串 print(time.strptime("20170908 182719","%Y%m%d %H%M%S"))#将格式化的时间转换成时间元组 print(datetime.datetime.now()) #当前时间格式化输出 print(datetime.datetime.now()+datetime.timedelta(3)) #3天后的时间 print(datetime.datetime.now()+datetime.timedelta(-3)) #3天前的时间

     五、shelve模块

    shelve模块用来持久化存储数据,shelve模块可以存储list、字典、函数、类等,shelve模块是key-value存储的,value是存储内容。

    import shelve
    
    s = shelve.open('shelve_test', 'r')   
    
    class Test(object):
    
        def __init__(self, n):
    
            self.n = n
    
    t = Test(1234)
    t1 = Test('abcd')
    
    def func():
    
         print('hello world')
    
    name = ['tom', 'jane', 'rose']
    
    d['test'] = name
    d['t'] = t
    d['t1'] = t1
    d['t2'] = func
    
    print(d.get('t2'))
    d.close()

     六、hashlib模块

    hashlib模块,主要用于加密相关操作,主要提供sha1、sha256、sha384、sha512、MD5算法

    import hashlib
    
    m = hashlib.md5()
    m.update(b"hello, linda")
    m.update(b"it's me")
    print(m.digest())
    m.update(b"It has been a long time since we ... ")
    
    print(m.digest())   #2进制hash
    print(len(m.hexdigest()))  #16进制hash
    
    hash = hashlib.md5()
    hash.update(b'admin')
    print(hash.hexdigest())
    
    hash = hashlib.sha1()
    hash.update(b'admin')
    print(hash.hexdigest())
    
    hash = hashlib.sha256()
    hash.update(b'admin')
    print(hash.hexdigest())
    
    hash = hashlib.sha384()
    hash.update(b'admin')
    print(hash.hexdigest())
    
    hash = hashlib.sha512()
    hash.update(b'admin')
    print(hash.hexdigest())

    七、configparser模块

    configparser模块用来操作配置文件,用于生成和修改配置文件,python2中为ConfigParser。

    常见的配置文件如下:

    [DEFAULT]
    ServerAliveInterval = 45
    Compression = yes
    Compressionlevel = 9
    ForwardX11 = yes
    
    [bitbucket.org]
    User = hg
    
    [topsecret.server.com]
    Port = 50022
    ForwardX11 = no

    使用configparser模块可以生成一个这样的文档:

    import configparser
    
    class myconf(configparser.ConfigParser):
        def __init__(self):
            configparser.ConfigParser.__init__(self, defaults=None)
        def optionxform(self, optionstr):
            return optionstr
        
    config = myconf()
    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['Port'] = '50022'
    topsecret['ForwardX11'] = 'no'
    config['DEFAULT']['ForwardX11'] = 'yes'
    with open('my.conf', 'w') as configfile:
        config.write(configfile)

     以下是一些常用的操作,修改、添加、删除节点和属性

    import configparser
    
    class myconf(configparser.ConfigParser):
        def __init__(self):
            configparser.ConfigParser.__init__(self, defaults=None)
        def optionxform(self, optionstr):
            return optionstr
    
    config = myconf()
    
    config.read('my.conf')
    
    sections = config.sections()  # 获取所有节点
    
    print(sections)
    
    items = config.items('DEFAULT')  # 获取指定节点下的所有键值对
    
    print(items)
    
    options = config.options('bitbucket.org')  # 获取指定节点下的所有键(DEFAULT默认节点下的键也会展示)
    
    print(options)
    
    print(config.get('bitbucket.org', 'User'))  # 获取对应节点下的key值
    
    config.add_section('NEW')  # 增加节点
    
    config.set('NEW', 'test', 'true')  # 增加节点下面对应的属性和值
    
    config.set('DEFAULT', 'hk', '2333')  # 修改节点下的属性
    
    with open("my.conf", "w") as d:  # 写入修改后的文件
        config.write(d)
    
    print(config.has_option('NEW', 'test'))  # 节点下是否有对应的属性
    
    print(config.has_section('NEW'))  # 是否有该节点
    
    config.remove_section('NEW')  # 删除节点
    
    config.write(open("my.conf", "w"))  # 把删除写入文件
    
    d.close()

    运行结果:

    ['bitbucket.org', 'topsecret.server.com']
    [('ServerAliveInterval', '45'), ('Compression', 'yes'), ('CompressionLevel', '9'), ('ForwardX11', 'yes')]
    ['User', 'ServerAliveInterval', 'Compression', 'CompressionLevel', 'ForwardX11']
    hg
    True
    True

    八、re模块

    re模块是正则表达式模块,用来匹配一些特定的字符串。

    以下是一些常用的正则表达式符号

    '.'        默认匹配除
    之外的任意一个字符,若指定 flag DOTALL,则可以匹配任意字符。
    '^'        匹配字符开头,若指定flag MULTILINE,这种可以匹配上(r"^a", "
    abc
    eee", flag=re.MULTILINE)
    '$'        匹配字符结尾,或e.search("foo$", "bfoo
    sdfsf", flags=re.MULTILINE).group()也可以
    '*'        匹配*号前的字符0次或多次,re.findall("ab*", "cabb3abcbbac") 结果为['abb', 'ab', 'a']
    '+'        匹配前一个字符1次或多次,re.findall("ab+", "ab+cd+abb+bba") 结果为['ab', 'abb']
    '?'        匹配前一个字符1次或0次
    '{m}'      匹配前一个字符m次
    '{n, m}'   匹配前一个字符n到m次,re.findall("ab{1,3}", "abb abc abbcbbb") 结果['abb', 'ab', 'abb']
    '|'        匹配|左或|右的字符,re.search("abc|ABC", "ABCBabcCD").group() 结果['ABC']
    '(...)'    分组匹配,re.search("(abc){2}a(123|456)c", "abcabca456c").group() 结果 abccbaca456c
    'A'       只从字符开头匹配,re.search("Aabc", "alexabc") 匹配不到
    ''       匹配字符结尾,同$
    'd'       匹配数字0-9
    'D'       匹配非数字
    'w'       匹配[A-Za-z0-9]
    'W'       匹配非[A-Za-z0-9]
    's'        匹配空白字符、	、
    、
    ,re.search("s+", "ab	c1
    3").group() 结果 	

    常用的匹配语法:

    re.match     #从头开始匹配
    re.search    #匹配包含
    re.findall   #把所有匹配到的字符放到列表以元素的形式展示
    re.splitall  #以匹配到的字符当做列表分隔符
    re.sub       #匹配字符并替换

     九、xlrd、xlwt、xlutils模块

    Python操作Excel文件需要xlrd、xlwt、xlutils等模块,xlrd用来读取Excel,xlwt用来写Excel,xlutils用来修改Excel,可以使用pip安装,也可以在pycharm的setting里安装。

    1、xlrd模块,具体用法如下:

    #!/usr/bin/env python
    # _*_ coding:utf-8 _*_
    import xlrd
    
    open_wb = xlrd.open_workbook('demo.xls')    # 打开Excel文件,该文件不存在会报错
    
    print(open_wb.sheet_names())    # 获取所有sheet页的名字
    
    sheet_name = open_wb.sheet_by_name('sheet1')  # 按照名字查找第二张表单
    
    sheet_index = open_wb.sheet_by_index(0)    # 根据sheet页的索引获取sheet内容
    
    print(sheet_name.nrows)    # 获取sheet_name的行数
    print(sheet_name.ncols)    # 获取sheet_name的列数
    
    for row_num in range(sheet_name.nrows):    # 循环获取每行的数据
        print(sheet_name.row_values(row_num))    # 获取每行数据
    
    cell_A2 = sheet_index.cell(1, 1).value    # 获取指定单元格的值,第一个值是行,第二个值是列
    
    print(cell_A2) 

    2、xlwt模块,用来写入Excel

    #!/usr/bin/env python
    # _*_ coding:utf-8 _*_
    import xlwt
    title = ['姓名', '年龄', '性别', '段位']
    status = [['德玛', '27', '', '青铜'], ['艾希', '26', '', '黄金'], ['亚瑟', '28', '', '白银']]
    
    new_wb = xlwt.Workbook()     # 新建一个Excel对象
    
    sheet = new_wb.add_sheet('Legends')     # 添加一个名为Legends的sheet页
    
    for i in range(len(title)):
        sheet.write(0, i, title[i])     # 写入表头
    
    for i in range(len(status)):
        for j in range(4):
            sheet.write(i+1, j, status[i][j])     # 循环写入每行数据
    new_wb.save('legend.xls')     # 保存数据到legend.xls中,不支持后缀为.xlsx的格式

    3、xlutils模块,修改Excel的内容,不能直接修改原来的Excel内容,需要先复制一个心得Excel文件,用法如下:

     1 #!/usr/bin/env python
     2 # _*_ coding:utf-8 _*_
     3 
     4 from xlrd import open_workbook     # 导入xlrd中的打开Excel模块
     5 from xlutils.copy import copy           # 导入xlutils.copy中的复制Excel模块
     6 open_wb = open_workbook('legend.xls')
     7 
     8 index_wb = open_wb.sheet_by_index(0)   # 通过索引获取sheet
     9 
    10 copy_wb = copy(open_wb)     # 复制一个Excel
    11 
    12 sheet_wb = copy_wb.get_sheet(0)    # 获取到新的Excel里面的sheet
    13 
    14 sheet_wb.write(1, 0, '蒙多')    # 修改原文件的第1行第0列为'蒙多'
    15 
    16 copy_wb.save('legend_new.xls')     # 保存新的Excel,后缀名为xls,不支持后缀名为xlsx
  • 相关阅读:
    数组初始化问题calloc和memset+malloc
    C++四种类型转换
    判断回文
    Linux运维三:系统目录结构
    Linux运维二:CentOS6.6系统安装后的基本配置与优化
    Linux运维一:生产环境CentOS6.6系统的安装
    Linux /etc/issue 和 /etc/issue.net的作用和区别
    linux内核参数注释与优化
    Linux中的文件描述符与打开文件之间的关系
    Linux Wget 命令实例讲解
  • 原文地址:https://www.cnblogs.com/wuxiaoyu-1537/p/7495963.html
Copyright © 2011-2022 走看看