• python3 os模块


    import os 
    
    
    """目录操作"""
    os.makedirs("a/b/c")  # 创建多级目录(推荐使用)
    os.removedirs("a/b/c")  # 删除多级目录(不推荐使用)
    os.mkdir("aa")  # 创建一级目录
    os.rmdir("aa")  # 删除一层目录
    os.listdir("./")  # 列出指定目录下的文件和文件夹
    os.getcwd()  # 获取当前工作目录
    os.chdir("aaa")  # 切换工作目录
    os.chdir("../")  
    os.path.join("a", "b") # 路径拼接 'a\b'
    os.path.basename("a/b/c")  # 返回最后一个/后面的内容 'c'
    os.path.basename("a/b/c.txt")  # 返回最后一个/后面的内容 'c.txt'
    os.path.dirname("a/b/c")  # 返回除最后一个/后面内容外的部分 'a/b'
    os.path.dirname(os.path.dirname("a/b/c"))  # 'a'
    os.path.split("a/b/c")  # 路径分隔('a/b', 'c')
    import os 
    
    
    """文件操作"""
    open("a.txt", "w", encoding="utf-8").close()  # 创建一个空文件
    os.rename("a.txt", "a-new.txt")  # 文件重命名
    os.remove("a-new.txt")  # 删除文件
    os.path.exists("a.txt")  # 判断文件或目录是否存在
    os.path.isfile("a.txt")  # 判断是否是文件
    os.path.isdir("a.txt")  # 判断是否是目录
    os.path.isabs("a.txt")  # 判断是否是绝对路径 
    os.path.abspath("a.txt")  # 文件的绝对路径 'G:\python28\code\day05\整理笔记\a.txt'
    os.path.getatime("b.txt")  # 文件最后访问的时间戳 
    os.path.getctime("b.txt")  # 文件最后修改的时间戳 
    os.path.getsize("b.txt")  # 文件大小,单位字节
    os.stat("b.txt")  # 文件信息
    os.stat_result(st_mode=33206, st_ino=14636698789298201, st_dev=2049124156, st_nlink=1, st_uid=0, st_gid=0, st_size=33, st_atime=1574923631, st_mtime=1574923730, st_ctime=1574923631)

    import os
    
    
    os.system("dir")  # 执行命令,无返回值
    os.popen("dir").read()  # 执行命令,有返回值
    os.sep  # 系统分隔符 '\'
    import os
    
    
    def list_dir(path): 
        """
        遍历目录下所有的文件
        """
        lst = os.listdir(path)
        for name in lst:
            file_path = os.path.join(path, name)
            if os.path.isdir(file_path):
                list_dir(file_path)
            else:
                print(file_path)
        
    list_dir("./")
    ./.ipynb_checkpoints整理笔记-checkpoint.ipynb
    ./.ipynb_checkpoints练习题-checkpoint.ipynb
    ./aaa1.txt
    ./aaa2.txt
    ./aaabba1.txt
    ./aaabba2.txt
    ./abca111.txt
    ./b.txt
    ./安装包.exe
    ./整理笔记.ipynb
    ./练习题.ipynb

    import os
    
    
    def list_dir(path, layer): 
        """
        遍历目录下所有的文件和目录
        """
        lst = os.listdir(path)
        for name in lst:
            file_path = os.path.join(path, name)
            if os.path.isdir(file_path):
                print((layer-1)*"	" + name)
                list_dir(file_path, layer+1)
            else:
                print((layer-1)*"	" + name)
        
    list_dir("./", 1)
    .ipynb_checkpoints
    	整理笔记-checkpoint.ipynb
    	练习题-checkpoint.ipynb
    88
    aaa
    	1.txt
    	2.txt
    	bbb
    		a1.txt
    		a2.txt
    abc
    	a111.txt
    b.txt
    安装包.exe
    整理笔记.ipynb
    练习题.ipynb

    import os
    
    
    def unit_convert(size):
        """
        字节、KB、MB、GB单位转换
        """
        if size > 1024*1024*1024:
            return format(size/1024/1024/1024, ".2f")+"GB"
        elif size > 1024*1024:
            return format(size/1024/1024, ".2f")+"MB"
        elif size > 1024:
            return format(size/1024, ".2f")+"KB"
        else:
            return str(size)+"B"
        
    
    
    def getPathSize(path): 
        """
        统计目录的总大小
        """
        total_size = 0
        def get_size(path):         
            nonlocal total_size
            lst = os.listdir(path)
            for name in lst:
                file_path = os.path.join(path, name)
                if os.path.isdir(file_path):
                    total_size += os.path.getsize(file_path)
                    print(file_path)
                    get_size(file_path)
                else:
                    print(file_path)
                    total_size += os.path.getsize(file_path)
            return total_size
        return get_size(path)
          
       
    print(unit_convert(getPathSize("./")))
    ./.ipynb_checkpoints
    ./.ipynb_checkpoints整理笔记-checkpoint.ipynb
    ./.ipynb_checkpoints练习题-checkpoint.ipynb
    ./88
    ./aaa
    ./aaa1.txt
    ./aaa2.txt
    ./aaabb
    ./aaabba1.txt
    ./aaabba2.txt
    ./abc
    ./abca111.txt
    ./b.txt
    ./安装包.exe
    ./整理笔记.ipynb
    ./练习题.ipynb
    29.95KB

    import os
    
        
    os.walk("./")  # 返回一个生成器
    print(list(os.walk("./")))  # [root, [文件夹1,文件夹2...], [文件1,文件2...]]
    [('./', ['.ipynb_checkpoints', '88', 'aaa', 'abc'], ['b.txt', '安装包.exe', '整理笔记.ipynb', '练习题.ipynb']), ('./.ipynb_checkpoints', [], ['整理笔记-checkpoint.ipynb', '练习题-checkpoint.ipynb']), ('./88', [], []), ('./aaa', ['bbb'], ['1.txt', '2.txt']), ('./aaa\bbb', [], ['a1.txt', 'a2.txt']), ('./abc', [], ['a111.txt'])]

    import os
    
    
    def getPathSize(path): 
        """
        统计目录的总大小
        """
        total_size = 0
        gen = os.walk(path)  # 拿到一个生成器
        for root,  dirs, files in gen:
            for d in dirs:            
                dir_path = os.path.join(root, d)
                total_size += os.path.getsize(dir_path)
                print(dir_path)
            for f in files:
                file_path = os.path.join(root, f)
                total_size += os.path.getsize(file_path)
                print(file_path)
        return total_size
    
    print(unit_convert(getPathSize("./")))
    ./.ipynb_checkpoints
    ./88
    ./aaa
    ./abc
    ./b.txt
    ./安装包.exe
    ./整理笔记.ipynb
    ./练习题.ipynb
    ./.ipynb_checkpoints整理笔记-checkpoint.ipynb
    ./.ipynb_checkpoints练习题-checkpoint.ipynb
    ./aaabb
    ./aaa1.txt
    ./aaa2.txt
    ./aaabba1.txt
    ./aaabba2.txt
    ./abca111.txt
    30.05KB
  • 相关阅读:
    Codeforces Round #368 Div. 2
    TXT文件去除多余空行
    #4247. 串
    #4322. 字符串游戏(strgame)
    #4214. 谢特
    #4155. 咱们去烧菜吧
    #4350. 「十二省联考 2019」字符串问题
    #4349. 「十二省联考 2019」异或粽子
    #4303. 跳蚤
    #4302. 魔法咒语
  • 原文地址:https://www.cnblogs.com/lilyxiaoyy/p/10795012.html
Copyright © 2020-2023  润新知