照常每日一撸:主要是熟练递归和绝对路径的运用。
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)
输出效果如下: