python文件夹遍历判断

1. 遍历该目录下所有子目录,找到所有的文件。 2. 二进制方式读取文件开头,找到文件特征。 3. 根据特征判断该文件的类型,并和文件后缀对照。 4. 创建**正常**和**异常**两个文件夹。 5. 特征符合后缀的正常文件放在**正常**文件夹,特征不符合的放在**异常**文件夹。

import os

def get_file(root_path,all_files=[]):
    '''
    递归函数,遍历该文档目录和子目录下的所有文件,获取其path
    '''
    files = os.listdir(root_path)
    for file in files:
        if not os.path.isdir(root_path + '/' + file):   # not a dir
            all_files.append(root_path + '/' + file)
        else:  # is a dir
            get_file((root_path+'/'+file),all_files)
    return all_files

# example
path = './raw_data'
print(get_file(path))