python - 为什么文件搜索时递归不完全?
大家讲道理
大家讲道理 2017-04-18 09:50:23
0
1
622
import os
#os.chdir('C:\Users\Administrator\Desktop\\TEST')


def search(keyword,pathname):
    for f in os.listdir(pathname):
        if os.path.isfile(f):
            if keyword in f:
                print os.path.join(pathname,f)
        if os.path.isdir(f):
            os.chdir(os.path.join(pathname,f))
            pathname=os.getcwd()
            search(keyword,pathname=os.getcwd())
    

if __name__ == "__main__":
    keyword=raw_input('input:')
    pathname=os.getcwd()
    search(keyword,pathname)

本人欲用递归的方式查询并输出文件名中含有关键词的文件,可是此处代码运行后却只能搜索当前目录下的文件,而符合要求的二级、三级目录内的文件却无法检验出?已修改多次,然问题依旧,请相关爱好者及行业从业者交流、指正,谢谢!

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

reply all(1)
小葫芦

Path problem, please note that the path of the file refers to the complete path, not the string in os.listdir. The corrected procedure is as follows:

import os

def search(keyword,pathname):
    for f in os.listdir(pathname):
        real_path = os.path.join(pathname,f)
        if os.path.isfile(real_path):
            if keyword in f:
               print real_path
        if os.path.isdir(real_path):
            search(keyword,real_path)

if __name__ == "__main__":
    keyword=raw_input('input:')
    pathname=os.getcwd()
    search(keyword,pathname)
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template