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


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 %   


评论关闭