Discuss / Python / 第二题:利用os.walk目录遍历器 六行代码实现功能

第二题:利用os.walk目录遍历器 六行代码实现功能

Topic source

应该是最简了吧。os.walk这里没有讲,但很实用的一个方法

import os
sr = input('关键字符串:')
for path, dirs, files in os.walk("."):
    for a in files + dirs:
        if sr in a:
            print(os.path.join(path, a))

一段代码看懂os.walk用法:

import os

x = os.walk(".")  # 遍历 ‘.’ 路径下目录及文件
print(x)  # 输出三元列表# ('.', ['dir_1', 'dir_2'], ['file_1', 'file_2', 'file_3'])

for a, b, c in x:
    print(a)  # 正在遍历的目录# '.'
    print(b)  # 被遍历目录下的子目录# ['dir_1', 'dir_2']
    print(c)  # 被遍历目录下的文件# ['file_1', 'file_2', 'file_3']
    break

d = next(x)  # 遍历子目录'dir_1'
e = next(x)  # 遍历子目录'dir_2'
f = next(x)  # 遍历子目录'dir_1'下的子目录'...'
# ''''''
print('{}\n{}\n{}'.format(d, e, f))  # 目录名文件名是瞎编的,具体输出情况以实际为准




  • 1

Reply