Python中的目录遍历工具
OS 模块的os.walk()
方法可用于列出所有目录。此方法基本上在目录树中自上而下或自下而上生成文件名。对于以目录 top 为根的树中的每个目录(包括 top 本身),它会产生一个 3 元组(dirpath、dirnames、filenames)。
- dirpath:一个字符串,它是目录的路径
- dirnames:根目录下的所有子目录。
- 文件名:来自根目录和目录的所有文件。
Syntax: os.walk(top, topdown=True, onerror=None, followlinks=False)
Parameters:
top: Starting directory for os.walk().
topdown: If this optional argument is True then the directories are scanned from top-down otherwise from bottom-up. This is True by default.
onerror: It is a function that handles errors that may occur.
followlinks: This visits directories pointed to by symlinks, if set to True.
Return Type: For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames, filenames).
示例:假设目录如下所示:
我们要列出目录树中的所有子目录和文件。下面是实现。
# Python program to list out
# all the sub-directories and files
import os
# List to store all
# directories
L = []
# Traversing through Test
for root, dirs, files in os.walk('Test'):
# Adding the empty directory to
# list
L.append((root, dirs, files))
print("List of all sub-directories and files:")
for i in L:
print(i)
输出:
List of all sub-directories and files:
('Test', ['B', 'C', 'D', 'A'], [])
('Test/B', [], [])
('Test/C', [], ['test2.txt'])
('Test/D', ['E'], [])
('Test/D/E', [], [])
('Test/A', ['A2', 'A1'], [])
('Test/A/A2', [], [])
('Test/A/A1', [], ['test1.txt'])
上面的代码可以使用 List Comprehension 来缩短,这是一种更 Pythonic 的方式。下面是实现。
# Python program to list out
# all the sub-directories and files
import os
# List comprehension to enter
# all directories to list
L = [(root, dirs, files) for root, dirs, files, in os.walk('Test')]
print("List of all sub-directories and files:")
for i in L:
print(i)
输出:
List of all sub-directories and files:
('Test', ['B', 'C', 'D', 'A'], [])
('Test/B', [], [])
('Test/C', [], ['test2.txt'])
('Test/D', ['E'], [])
('Test/D/E', [], [])
('Test/A', ['A2', 'A1'], [])
('Test/A/A2', [], [])
('Test/A/A1', [], ['test1.txt'])