Python 扫描目录及该目录包含所有目录的文件

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wang725/article/details/84844059

参考
用到函数:os.walk(path)
os.walk()可以得到一个三元tupple(dirpath,sub_dirs, filenames),其中第一个为起始路径,第二个为起始路径下的所有文件夹,第三个是起始路径下的所有文件。
其中dirpath是一个string,代表目录的路径,sub_dirs是一个list,包含了dirpath下所有子目录的名字。filenames是一个list,包含了非目录文件的名字。这些名字不包含路径信息,如果需要得到全路径,需要使用os.path.join(dirpath, name).

import os

def print_dir_files(file_path):
    file_lst = []
    for file_path, sub_dirs, filenames in os.walk(file_path):
        if filenames:
            # 如果是文件,则加append到list中
            for filename in filenames:
                file_lst.append(os.path.join(file_path, filename))
        for sub_dir in sub_dirs:
            # 如果是目录,则递归调用该函数
            print_dir_files(sub_dir)
    for file_lst_item in file_lst:
        print file_lst_item

if __name__ == '__main__':
    file_path = '/home/wfq/temp'
    print_dir_files(file_path)

运行结果

/home/wfq/temp/dir_1/file_11_1
/home/wfq/temp/dir_1/file_11
/home/wfq/temp/dir_1/file_11_11
/home/wfq/temp/dir_1/dir_11/file_12
/home/wfq/temp/dir_1/dir_11/file_123
/home/wfq/temp/dir_1/dir_11/dir_111/file_111_1
/home/wfq/temp/dir_1/dir_11/dir_111/file_111
/home/wfq/temp/dir_1/dir_11/dir_111_1/c
/home/wfq/temp/dir_1/dir_11/dir_111_1/a
/home/wfq/temp/dir_1/dir_11/dir_111_1/b
/home/wfq/temp/ops/db.sqlite3
/home/wfq/temp/ops/manage.py
/home/wfq/temp/ops/ops/settings.py
/home/wfq/temp/ops/ops/wsgi.py
/home/wfq/temp/ops/ops/urls.py
/home/wfq/temp/ops/ops/__init__.py
/home/wfq/temp/ops/ops/__pycache__/__init__.cpython-36.pyc
/home/wfq/temp/ops/ops/__pycache__/urls.cpython-36.pyc
/home/wfq/temp/ops/ops/__pycache__/settings.cpython-36.pyc

猜你喜欢

转载自blog.csdn.net/wang725/article/details/84844059
今日推荐