首页 > 解决方案 > 检查文件是否在子目录中?

问题描述

我想检查给定文件是否在特定目录中,并且它包括子目录。

我使用了这段代码:

def Grep(givenfile,givendir):
    # iterate top down till in directory path
    for (root,dirs,files) in os.walk(givendir):
        if givenfile in files:
            # if file present return true
            return True
    return False

## Test.py my file that contain my code 
##C://Users//LENOVO//Desktop//python2021 this my path that contain my files 
Grep("Test.py",r"C://Users//LENOVO//Desktop//python2021")

当我运行没有显示输出的代码时?

有没有更好的方法来检查给定文件是否在特定目录中并且它是否包含子目录

谢谢

标签: python

解决方案


没有输出,因为您没有打印任何内容。试试这个作为最后一行:

print(Grep("Test.py",r"C://Users//LENOVO//Desktop//python2021"))

推荐阅读