美文网首页
Python 遍历文件夹及子文件夹

Python 遍历文件夹及子文件夹

作者: 梁景华Joshua_ | 来源:发表于2019-04-17 18:15 被阅读0次

    在游戏公司搞SDK,需要搞混淆(你懂的),闲来无事研究Python..
    Mark第一步
    方法一:

    #!/usr/bin/env python3
    # coding:utf-8
    
    import os
    
    _defaultList = [".h",".m"]
    
    def list_all_files(path):
    
        if not os.path.isdir(path) and not os.path.isfile(path):
            return False
    
    #只要.h,.m文件
    # if os.path.isfile(path) and os.path.splitext(path)[-1] in _defaultList and os.path.splitext(os.path.basename(path))[0] not in _files: 
        if os.path.isfile(path) : #文件
            print(path)
        elif os.path.isdir(path): #文件夹
            for i in os.listdir(path): #递归
                list_all_files(os.path.join(path,i))
        return True
    
    def list_all_files_do_something(path):
        if list_all_files(path) == True:
            print(_files)
            #下一步操作
        else:
            print("非法")
    
    if __name__ == '__main__':
        path = "/文件夹路径"
        list_all_files_do_something(path)
    
    

    方法二:

    _files = []
    _defaultList = [".h",".m"]
    def list_all_files(path):
        if not os.path.isdir(path) and not os.path.isfile(path):
            # print("非法")
            return False
    
        for root, dirs, files in os.walk(path):
            for name in dirs: #目录
                print("dirs",os.path.join(root, name))
            for name in files: #文件
                print("dirs",os.path.join(root, name))
    
        return True
    
    def list_all_files_do_something(path):
        if list_all_files(path):
            print(_files)
        else:
            print("非法")
    
    if __name__ == '__main__':
        path = "/文件夹路径"
        list_all_files_do_something(path)
    
    

    方法二文档:http://www.runoob.com/python3/python3-os-walk.html

    相关文章

      网友评论

          本文标题:Python 遍历文件夹及子文件夹

          本文链接:https://www.haomeiwen.com/subject/sqfowqtx.html