#coding=utf-8 import os import re c_dir = [] txt_files = [] def search_files(dir,key): dir = dir c_dir.append(dir) os.chdir(dir) all_files = os.listdir(os.curdir) keys = re.compile(r"%s" % key) for each_file in all_files: if os.path.isfile(each_file): f = open(each_file,'r') details = f.read() if keys.findall(details): txt_files.append(os.path.join(os.getcwd(),each_file)) elif os.path.isdir(each_file): search_files(os.path.join(os.getcwd(),each_file),key) os.chdir(os.pardir) dir = raw_input("请输入查看的目录:") key = raw_input("请输入要查找的关键字") search_files(dir,key) print(txt_files)