zoukankan      html  css  js  c++  java
  • 3.30---time、random、sys、os 模块练习

    1、检索文件夹大小

    要求执行方式如下:

    python3.8 run.py 文件夹
    import os
    import sys
    
    def file_size(file_path):
        size = 0
        if not os.path.isdir(file_path):
            return
        file_list = os.listdir(file_path)
        for name in file_list:
            son_path = os.path.join(file_path, name)
            if os.path.isdir(son_path):
                size += file_size(son_path)
            # elif os.path.isfile(son_path):
            else:
                size += os.path.getsize(son_path)
        return size
    
    file_path = sys.argv[1]
    size_of_file = file_size(file_path)
    print(size_of_file)

    2、随机验证码

    import random
    # 随机验证码
    def random_code(size=4):
        code = ""
        for i in range(size):
            alp_up = chr(random.randint(65,90))
            alp_low = chr(random.randint(97,122))
            num = str(random.randint(0,9))
    
            # 第二个列表weights=[]中存放各元素权重,k为选取次数.返回值为列表
            single_code = random.choices([alp_low,alp_up,num],weights=[1,1,2],k=2)
            code += single_code[0]
        return code
    
    print(random_code())

    3、模拟下载进度条

    import time
    def download():
        total = 50000
        speed = 1024
        acum = 0
        while acum < total:
            time.sleep(0.1)
            acum += speed
    
            percent = acum / total
            if percent > 1:
                percent = 1
            wide = int(percent*50)
            show_str = "#"*wide
            # 每次都覆盖前一次的打印结果,实现动态效果。percent*100显示加载百分比
            print("
    [%-50s] %d%%" %(show_str,percent*100),end="")
            
    download()

    4、文本copy脚本

    # 法一:
    import sys
    src_file = sys.argv[1]
    dst_file = sys.argv[2]
    
    with open(src_file,mode="rb") as f,
        open(dst_file,mode="wb") as f1:
        f1.write(f.read())
    #====================================
    # 法二:
    import sys
    import shutile
    src_file = sys.argv[1]
    dst_file = sys.argv[2]
    
    shutil.copyfile(src_file, dst_file)
  • 相关阅读:
    第四天——列表(一)
    第十二天—collections模块(十二)
    第十二天——sys模块(十)
    第十二天——os模块(九)
    第十二天——序列化模块(八)
    第十二天——random模块(七)
    第十二天——from ... import ...的使用(三)
    第十二天——import 使用(二)
    vue系列---------vuejs基础学习1.0
    前端随心记---------谈谈开发的工作规范
  • 原文地址:https://www.cnblogs.com/zhubincheng/p/12601588.html
Copyright © 2011-2022 走看看