zoukankan      html  css  js  c++  java
  • python-第二块:random、shutil,json & pickle,shelve模块

    Random module

    import random,string
    print(random.random())             #随机打印小数
    print(random.randint(1,3))         #随机打印范围内整数(包含后面的3)
    print(random.randrange(1,3))       #随机打印范围内整数(不包含后面的3)
    print(random.sample(range(100),2)) #100里随机挑选两个数
    
    str_source = string.ascii_letters + string.digits
    check_word = ""
    for i in range(6):
        check_num = random.randrange(0,6)
        if check_num != i:
            temp = chr(random.randint(65,90))
        else:
            temp = chr(random.randint(0,9))
        check_word +=str(temp)
    print(check_word)
    

      random是随机选取模块,后面有关小程序可以随机生成6位数验证码

    Shutil module

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

    import shutil  #高级的文件、文件夹、压缩包 处理模块
    with open("文件名") as f1,open("文件名","w") as f2:
        shutil.copyfileobj(f1,f2)                              #将对象1拷贝为对象2
    
    shutil.copy()               #拷贝文件
    shutil.copytree()             #拷贝目录
    shutil.rmtree()               #递归删除
    shutil.make_archive(base_name,format......)         #打包 ,base_name:压缩的文件名
    

      目前对于shutil模块的使用较少,用过shutil来备份文件。

    Json&Pickle module 

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

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

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

      首先使用json或pickle序列化

    #序列化
    import json     #json模块通用于各大语言,使用json进行转换
    import pickle   #只适应于python
    
    info ={
        "name":"dzk",
        "age":23
    }
    
    f = open("test","w")
    f.write(json.dumps(info))  # == json.dump(info,f)
    f.close()
    

      然后使用json或pickle反序列号

    #序列化
    import json     #json模块通用于各大语言,使用json进行转换
    import pickle
    
    f = open("test","r")
    date = json.loads(f.read())   # == json.load(f)
    print(date)
    f.close()
    

    Shelve module

      shelve模块是一个简单的k,v将内存数据通过文件持久化的模块,可以持久化任何pickle可支持的python数据格式

    import shelve
    
    def date(name,age):
        print("hello",name,age)
    
    f = shelve.open("shelve_test")
    
    print(f["she_dict"])
    print(f["she_list"])
    print(f["she_def"]("dzk",23))
    

      最后会生成三个文件,shelve_test.bak,shelve_test.bat,shelve_test.dir      

    文件内容为:

    'she_list', (512, 35)
    'she_dict', (0, 45)
    'she_def', (1024, 20)

    这个模块功能暂没用过
  • 相关阅读:
    layer 弹出层 回调函数调用 弹出层页面 函数
    jquery 封装页面之间获取值
    ZTree 获取选中的项
    动态拼接SQL 语句
    翻译-使用Spring调用SOAP Web Service
    分享最新的博客到LinkedIn Timeline
    翻译-使用Spring WebService生成SOAP Web Service
    在Gradle中使用jaxb的xjc插件
    Gradle中的buildScript代码块
    健身4个月总结
  • 原文地址:https://www.cnblogs.com/japhi/p/6894891.html
Copyright © 2011-2022 走看看