频道栏目
首页 > 资讯 > Python > 正文

Python语言获取目录下所有文件或目录的方法

14-02-27        来源:[db:作者]  
收藏   我要投稿

Python的os.listdir()可以获取当前目录下的所有文件和目录,但不支持递归。有时候希望获取以递归方式指定目录下所有文件列表,为此可以调用下面的get_recursive_file_list()函数。


文件名: file_util.py

#! /usr/bin/python

'''
Utilities of file & directories.
'''

import os

# Get the all files & directories in the specified directory (path).
def get_recursive_file_list(path):
    current_files = os.listdir(path)
    all_files = []
    for file_name in current_files:
        full_file_name = os.path.join(path, file_name)
        all_files.append(full_file_name)

        if os.path.isdir(full_file_name):
            next_level_files = get_recursive_file_list(full_file_name)
            all_files.extend(next_level_files)

    return all_files


使用示例:

test@a_fly_bird /home/test/examples/python % ll
总用量 8
-rwxrwxrwx 1 test users 501  2月 26 20:04 file_util.py*
-rwxrwxrwx 1 test users 109  2月 26 20:04 test.py*
test@a_fly_bird /home/test/examples/python % mkdir aaa
test@a_fly_bird /home/test/examples/python % echo "first" > ./aaa/first.txt
test@a_fly_bird /home/test/examples/python % echo "second" > ./aaa/second.txt
test@a_fly_bird /home/test/examples/python % cat ./aaa/first.txt
first
test@a_fly_bird /home/test/examples/python % python
Python 3.2.3 (default, Sep  7 2012, 03:04:57) 
[GCC 4.7.1 20120721 (prerelease)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import file_util
>>> files = file_util.get_recursive_file_list(".")
>>> files
['./aaa', './aaa/second.txt', './aaa/first.txt', './file_util.py', './test.py', './__pycache__', './__pycache__/file_util.cpython-32.pyc']
>>> exit()
test@a_fly_bird /home/test/examples/python % ll
总用量 16
drwxr-xr-x 2 test users 4096  2月 26 20:06 aaa/
-rwxrwxrwx 1 test users  501  2月 26 20:04 file_util.py*
drwxr-xr-x 2 test users 4096  2月 26 20:06 __pycache__/
-rwxrwxrwx 1 test users  109  2月 26 20:04 test.py*
test@a_fly_bird /home/test/examples/python %   


相关TAG标签
上一篇:《C++ Primer第五版》读书笔记(9)--ASSOCIATIVE CONTAINERS
下一篇:输入n个数和输出调整后的n个数
相关文章
图文推荐

关于我们 | 联系我们 | 广告服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 | Vip技术培训 | 举报中心

版权所有: 红黑联盟--致力于做实用的IT技术学习网站