zoukankan      html  css  js  c++  java
  • Python3 获取当前目录下 所有文件的路径

    import os
    def all_files_path(rootDir):                       
        for root, dirs, files in os.walk(rootDir):     # 分别代表根目录、文件夹、文件
            for file in files:                         # 遍历文件
                file_path = os.path.join(root, file)   # 获取文件绝对路径  
                filepaths.append(file_path)            # 将文件路径添加进列表
            for dir in dirs:                           # 遍历目录下的子目录
                dir_path = os.path.join(root,dir)       # 获取子目录路径
                all_files_path(dir_path)               # 递归调用
    if __name__ == "__main__":
        filepaths = []   
        all_files_path(os.getcwd()) #获取当前目录
        #all_files_path("dirpath")手动替换目录
        with open('dir.txt', 'w') as f:
            for filepath in filepaths:
                f.write(filepath + '
    ')
    
    

    测试发现因为路径的遍历会存在重复。只想要文件直接

    import os
    def all_files_path(rootDir):                       
        for root, dirs, files in os.walk(rootDir):     # 分别代表根目录、文件夹、文件
            for file in files:                         # 遍历文件
                file_path = os.path.join(root, file)   # 获取文件绝对路径  
                filepaths.append(file_path)            # 将文件路径添加进列表
       
    if __name__ == "__main__":
        filepaths = []   
        all_files_path(os.getcwd()) #获取当前目录
        #all_files_path("dirpath")手动替换目录
        with open('dir.txt', 'w') as f:
            for filepath in filepaths:
                f.write(filepath + '
    ')
    
    安安静静变优秀。 --胖丫
  • 相关阅读:
    VS2012开发调试PHP扩展
    Android webapi
    拖动上传文件
    IE11被识别为mozilla
    jquery validate.js 不能验证
    如何安装或卸载 Internet Explorer 9?
    C# 操作IIS -App & AppPools
    Filewatcher
    Notepad++使用技巧
    u-boot-2012.04.01移植笔记——支持NAND启动
  • 原文地址:https://www.cnblogs.com/pangya/p/15061550.html
Copyright © 2011-2022 走看看