码迷,mamicode.com
首页 > 其他好文 > 详细

遍历目录

时间:2019-02-14 00:16:41      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:global   目录   join   files   lob   res   def   lis   col   

import os

root_path1 = rD:\python_code
file_count = 0
dir_count = 0


def list_files(root_path):
    """
    遍历目录
    :param root_path:
    :return:
    """
    global file_count, dir_count
    if os.path.isfile(root_path):
        print(root_path)
        file_count += 1
    else:
        res = os.listdir(root_path)
        for file in res:
            full_path = os.path.join(root_path, file)
            print(full_path)
            if os.path.isfile(full_path):
                print(full_path)
                file_count += 1
            else:
                dir_count += 1
                list_files(full_path)


def walk_files(root_path):
    """
    遍历目录
    :param root_path:
    :return:
    """
    global file_count, dir_count
    for root_dir, dirs, files in os.walk(root_path, topdown=True):
        for file in files:
            print(os.path.join(root_path, file))
            file_count += 1
        for dir1 in dirs:
            print(os.path.join(root_path, dir1))
            dir_count += 1


list_files(root_path1)
print(file_count)
print(dir_count)
print("----------------------")
walk_files(root_path1)
print(file_count)
print(dir_count)

 

遍历目录

标签:global   目录   join   files   lob   res   def   lis   col   

原文地址:https://www.cnblogs.com/sunBinary/p/10372399.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!