python递归法寻找文件内容

照常每日一撸:主要是熟练递归和绝对路径的运用。

def read_and_find_hello(py_file):  #读取文件并查找文件中是否包含“hello”字段
    flag = False
    f = open(py_file)
    while True:
        line = f.readline()
        if line == "":
            break
        elif "hello" in line:
            flag =  True
            break
    f.close()
    return flag

file_list = []
def find_hello(parent_file,file_name):
    file_abspath = os.path.join(parent_file,file_name)   #获得绝对路径
    if os.path.isdir(file_abspath):    #如果当前文件为一个目录
        for f in os.listdir(file_abspath):    #列出所有子文件
            find_hello(file_abspath,f)   #递归调用自己,继续判断是否为目录
    else:
        if file_abspath.endswith(".py"):
            if read_and_find_hello(file_abspath):
                file_list.append(file_abspath)

#a = read_and_find_hello("test.py")
#sys.setrecursionlimit(1000000)  #递归默认深度为1000,可以用此函数调节
find_hello("C:/Users/*/","Desktop")
print(file_list)

输出效果如下:



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值