每天进步一点点!加油哦!
#某个目录下找包含有某个关键字的文件
#在/root/my_code/ 文件夹下找所有包含“hello”且以“.py”结尾的文件 并显示其递归目录
import os
file_list=[]
#递归函数,该函数中所有的文件路径都采用绝对路径
def find_hello(parent_dir,file_name):#parent_dir文件所在的父目录的绝对路径,file_name表示当前要处理的文件或者目录
file_abspath=os.path.join(parent_dir,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"):#如果传入的文件是一个文件,判断文件名是不是.py
if read_and_find_hello(file_abspath):#读取该py结尾的文件 并且看文件是否包含hello
file_list.append(file_abspath)
def read_and_find_hello(py_file):#读其中的一个文件
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
find_hello("/root","my_code")
print(file_list)