get_files.py 1.65 KB
Newer Older
ligang committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
#!/usr/bin/env python3
#-*- coding:utf-8-*-
"""
2、自学文件判断、文件夹判断方法,完成函数get_files,能够递归的获取到给定文件或文件夹下的所有文件
 这里要考虑,给定的参数file_path是文件还是文件夹,如果是文件则直接列出来文件名称就可以
 如果是文件夹,那么要列出这个文件夹下所有的文件名称,同时要考虑,文件夹下是否还有文件夹
 直到保证此文件夹下再不包含文件夹,列出所有的文件名称即可
 # 每当读取一个文件夹时,打一个info级别的log,标记开始读取哪个文件夹
"""
import os
from homework.log.file_log import TNLog

def get_files(file_path):
    if os.path.exists(file_path):#判断文件是否存在
        if os.path.isdir(file_path):#判断是否为目录
            source_dir = os.listdir(file_path)
            for parents_file in source_dir:#列出文件夹下的所有文件以及文件夹
               child_file = os.path.join(file_path,parents_file)
               if os.path.isdir(child_file):#如为文件夹进行递归
                   logger.info("开始读取的文件夹为:" + child_file + '\n')
                   get_files(child_file)
               else:
                   print_file = '列出的文件为:%s' % (child_file) + '\n'
                   logger.info(print_file)
        elif os.path.isfile(file_path):
              print('列出的文件为:%s' % (file_path) +'\n')
        else:
            print ("it's a special file")
    else:
        print("file or dir not exists")

if __name__ == "__main__":
    old_path = 'F:/new_file'
    logger = TNLog()
    r = get_files(old_path)