鱼C论坛

 找回密码
 立即注册
查看: 1228|回复: 2

[已解决]求助! 查找文件的代码哪个环节逻辑出问题了?

[复制链接]
发表于 2020-3-5 15:45:43 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
代码如下:
#查找目录及子目录下所有的匹配文件
import os
def Find_Name(FindName, FilePath):
    for name in os.listdir(FilePath):
        if os.path.isdir(name):
            FilePath = os.path.join(FilePath_INT, name)
            Find_Name(FindName, FilePath)
        else:
            if name == FindName:
                print (os.path.join(FilePath, name))

   
FilePath_INT = r'C:\Users\Administrator\AppData\Local\Programs\Python\Python38-32\mine'
FindName = 'something.txt'

Find_Name(FindName, FilePath_INT)


运行后无法正常获取到目录下面的所有需要查找的文件,只会返回第一个匹配的文件。想了半天 不知道代码的逻辑哪错了

最佳答案
2020-3-6 23:52:58
修改如下,其中os.isdir判断的是绝对路径,你的事相对路径。
import os

def Find_Name(target, FilePath):
    print("当前目录:",FilePath)
    for name in os.listdir(FilePath):
        print("当前目录:%s,是否目录:%s"%(name,os.path.isdir(os.path.join(FilePath, name))))
        if os.path.isdir(os.path.join(FilePath, name)):
            print(name)
            Find_Name(target, os.path.join(FilePath, name))
        else:
            if name == target:
                print("符合条件的文件%s"%os.path.join(FilePath, name))
           

FilePath = r"C:\Users\Administrator\Desktop\123"
FindName ="2020.txt"

Find_Name(FindName, FilePath)
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2020-3-6 23:52:58 | 显示全部楼层    本楼为最佳答案   
修改如下,其中os.isdir判断的是绝对路径,你的事相对路径。
import os

def Find_Name(target, FilePath):
    print("当前目录:",FilePath)
    for name in os.listdir(FilePath):
        print("当前目录:%s,是否目录:%s"%(name,os.path.isdir(os.path.join(FilePath, name))))
        if os.path.isdir(os.path.join(FilePath, name)):
            print(name)
            Find_Name(target, os.path.join(FilePath, name))
        else:
            if name == target:
                print("符合条件的文件%s"%os.path.join(FilePath, name))
           

FilePath = r"C:\Users\Administrator\Desktop\123"
FindName ="2020.txt"

Find_Name(FindName, FilePath)
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2020-3-12 17:22:48 | 显示全部楼层
小小小菜菜菜 发表于 2020-3-6 23:52
修改如下,其中os.isdir判断的是绝对路径,你的事相对路径。

谢谢,搞明白了,是路径的问题
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-10-6 18:32

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表