python - 为什么文件搜索时递归不完全?

 撩人的东莞博文 发布于 2022-10-27 19:07
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)

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

1 个回答
  • 路径问题,注意文件的path是指完整的路径,而不是os.listdir中的字符串,修正后的程序如下:

    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)
    2022-10-29 04:34 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有