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

    import os
    print(os.getcwd()) #得到当前目录
    #os.chmod("/usr/local",7) #给文件或者文件夹加权限,7为最高权限
    print(os.chdir("../")) #更改当前目录
    print(os.curdir) #当前目录
    print(os.pardir) #父目录
    print(os.mkdir("test1")) #创建文件夹
    print(os.makedirs("usr/hehe/hehe1")) #递归创建文件夹,如果父目录不存在则创建父目录
    #print(os.makdirs(r"usr/hehe/hehe1")) #递归创建文件夹,如果父目录不存在则创建父目录,r代表元字符的意思
    print(os.removedirs("usr/hehe/hehe1")) #递归删除空目录
    print(os.rmdir("usr/hehe/hehe1")) #删除文件夹, 只能删除空文件夹
    print(os.remove("usr/hehe/hehe1")) #删除文件
    print(os.listdir('.')) #当前目录下的所有文件列表
    os.rename("test","test1")#重命名
    print(os.stat("len_os.py"))#获取文件信息
    print(os.sep)#当前操作系统的路径分隔符, windows的路径分隔符为\,lnux的路径分隔符为 /.
    print(os.linesep)#当前操作系统的换行符
    print(os.pathsep) # 当前系统的环境变量中每个路径的分隔符,linux是:,windows是;
    print(os.environ)#当前操作系统的环境变量
    print(os.name)#当前系统名称

    print(os.path.abspath(__file__)) # 获取绝对路径,__file__表示当前文件
    print(os.path.split("/usr/hehe/hehe.txt")) # 分割路径和文件名

    print(os.path.dirname("/usr/local")) # 获取父目录

    print(os.path.basename("/usr/local")) # 获取最后一级,如果是文件显示文件名,如果是目录显示目录名
    print(os.path.exists("/usr/local")) # 判断目录/文件是否存在

    print(os.path.isabs(".")) # 判断是否是绝对路径
    print(os.path.isfile("/usr/local")) # 判断是否是一个文件
    print(os.path.isdir("/usr/local")) # 是否是一个路径
    print(os.path.join("/root", 'hehe', 'a.sql')) # 拼接成一个路径
    print(os.path.getatime("len_os.py")) # 输出最近访问时间
    print(os.path.getmtime("len_os.py")) # 输出最近访问时间

    import sys
    sys.argv #获取命令行参数List,第一个元素是程序本身路径
    sys.exit(n) #退出程序,正常退出时exit(0),若exit('xxxxx),则推出并返回xxxxx
    sys.version #获取Python解释程序的版本信息
    sys.maxint #当前操作系统支持最大的Int值,32位和64位不同
    sys.path #返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
    sys.platform #返回操作系统平台名称
    sys.stdout.write('please:') # 向屏幕输出一句话
    val = sys.stdin.readline()[:-1] # 获取输入的值

    import random, string

    print(random.random()) # 随机浮点数,默认取0-1,不能指定范围
    print(random.randint(1, 20)) # 随机整数,1-20
    print(random.randrange(1, 20)) # 随机产生一个整数,1-19,它是顾头不顾尾的
    print(random.choice('x23serw4')) # 随机取一个元素
    print(random.sample('hello', 2)) # 从序列中随机取几个元素
    print(random.uniform(1, 9)) # 随机取浮点数,可以指定范围
    x = [1, 2, 3, 4, 6, 7]
    random.shuffle(x) # 洗牌,打乱顺序,会改变原list的值
    print(x)
    print(string.ascii_letters + string.digits) # 所有的数字和字母

    import datetime, time

    print(time.timezone) # 和标准时间相差的时间,单位是s
    print(time.time()) # 获取当前时间戳,即从linux元年到现在的秒数, 常用格式为int(time.time()),取整
    print(time.sleep(1)) # 休息几s

    print(time.gmtime()) # 把时间戳转换成时间元组,如果不传的话,默认取标准时区的时间戳
    print(time.localtime()) # 把时间戳转换成时间元组,如果不传的话,默认取当前时区的时间戳
    print(time.mktime(time.localtime())) # 把时间元组转换成时间戳

    print(time.strftime("%y%m%d %H%M%S")) # 将时间元组转换成格式化输出的字符串
    print(time.strptime("20160204 191919", "%Y%m%d %H%M%S")) # 将格式化的时间转换成时间元组

    print(time.struct_time) # 时间元组
    print(time.asctime()) # 时间元转换成格式化时间
    print(time.ctime()) # 时间戳转换成格式化时间
    print(datetime.datetime.now()) # 当然时间格式化输出
    print(datetime.datetime.now() + datetime.timedelta(3)) # 3天后的时间
    print(datetime.datetime.now() + datetime.timedelta(-3)) # 3天前的时间

    import json

    dic = {"name": "niuniu", "age": 18}
    print(json.dumps(dic)) # 把字典转成json串
    fj = open('a.json', 'w')
    print(json.dump(dic, fj)) # 把字典转换成的json串写到一个文件里面
    s_json = '{"name":"niuniu","age":20,"status":true}'
    print(json.loads(s_json)) # 把json串转换成字典
    fr = open('b.json', 'r')
    print(json.load(fr)) # 从文件中读取json数据,然后转成字典

    import hashlib

    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进制格式hash
    print(len(m.hexdigest()))  # 16进制格式hash
    # ######## 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())


    import shelve
    d = shelve.open('shelve_test') #打开一个文件
    class Test(object):
    def __init__(self,n):
    self.n = n
    t = Test(123)
    t2 = Test(123334)
    def func():
    print('hello')
    name = ["alex","rain","test"]
    d["test"] = name #持久化列表
    d["t1"] = t #持久化类
    d["t2"] = t2
    d["t3"] = func
    print(d.get("t3"))#获取内容
    d.close()

    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)

    import configparser


    config = configparser.ConfigParser()
    config.read('my.cnf')
    sections = config.sections() # 获取所有节点
    print(config.get('bitbucket.org', 'User')) # 取对应节点下面key的值
    config.add_section('NEW') # 增加节点
    config.set('NEW', 'test', 'true') # 增加节点下面对应的熟悉和值
    config.set('DEFAULT', 'niu', '222222') # 修改节点下的属性
    config.write(open("my.cnf", "w")) # 写入修改后的文件
    config.has_option('NEW', 'test') # 节点下是否有对应的属性
    config.has_section('NEW') # 是否有该节点
    config.remove_section('NEW') # 删除节点
    config.remove_option('NEW', 'test') # 删除节点下面的key

    '''
    re 模块
    '.'
    默认匹配除 之外的任意一个字符,若指定flag
    DOTALL, 则匹配任意字符,包括换行
    '^'
    匹配字符开头,若指定flags
    MULTILINE, 这种也可以匹配上(r"^a", " abc eee", flags=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()
    结果
    abcabca456c
    '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 #匹配字符并替换


    if __name__='__main__': # 只有在运行自己这个Python文件的时候,才会执行下面的代码,在别的模块里面导入的时候是不会执行的
    __mokuai__
     
    
    
  • 相关阅读:
    我对IOC控制反转,依赖注入原理的理解
    .net带事件的对象BinaryFormatter 序列化失败
    (维权成功,链接已经被删除了)如何防止自己的原创文章被垃圾站IT165采集和盗用
    浅谈.net多线程机制
    给现下流行的打车软件的一点小建议
    C#应用MemoryStream提高File读取速度
    微软真的要抛弃Silverlight了吗?
    C# File.Copy 实现磁盘间文件备份
    遮罩層 日曆效果
    GridView導出Excel
  • 原文地址:https://www.cnblogs.com/yuer011/p/7044711.html
Copyright © 2011-2022 走看看