如何用Python实现在文件夹下查找一个关键词
2个回答
展开全部
#!/usr/bin/python
#coding:utf8
import os
#判断文件中是否包含关键字,是则将文件路径打印出来
def is_file_contain_word(file_list, query_word):
for _file in file_list:
if query_word in open(_file).read():
print _file
print("Finish searching.")
#返回指定目录的所有文件(包含子目录的文件)
def get_all_file(floder_path):
file_list = []
if floder_path is None:
raise Exception("floder_path is None")
for dirpath, dirnames, filenames in os.walk(floder_path):
for name in filenames:
file_list.append(dirpath + '\\' + name)
return file_list
query_word = raw_input("Please input the key word that you want to search:")
basedir = raw_input("Please input the directory:")
is_file_contain_word(get_all_file(basedir), query_word)
raw_input("Press Enter to quit.")
请采纳
#coding:utf8
import os
#判断文件中是否包含关键字,是则将文件路径打印出来
def is_file_contain_word(file_list, query_word):
for _file in file_list:
if query_word in open(_file).read():
print _file
print("Finish searching.")
#返回指定目录的所有文件(包含子目录的文件)
def get_all_file(floder_path):
file_list = []
if floder_path is None:
raise Exception("floder_path is None")
for dirpath, dirnames, filenames in os.walk(floder_path):
for name in filenames:
file_list.append(dirpath + '\\' + name)
return file_list
query_word = raw_input("Please input the key word that you want to search:")
basedir = raw_input("Please input the directory:")
is_file_contain_word(get_all_file(basedir), query_word)
raw_input("Press Enter to quit.")
请采纳
展开全部
port os
#判断文件中是否包含关键字,是则将文件路径打印出来
def is_file_contain_word(file_list, query_word):
for _file in file_list:
if query_word in open(_file).read():
print _file
print("Finish searching.")
#返回指定目录的所有文件(包含子目录的文件)
def get_all_file(floder_path):
file_list = []
if floder_path is None:
raise Exception("floder_path is None")
for dirpath, dirnames, filenames in os.walk(floder_path):
for name in filenames:
file_list.append(dirpath + '\\' + name)
return file_list
#判断文件中是否包含关键字,是则将文件路径打印出来
def is_file_contain_word(file_list, query_word):
for _file in file_list:
if query_word in open(_file).read():
print _file
print("Finish searching.")
#返回指定目录的所有文件(包含子目录的文件)
def get_all_file(floder_path):
file_list = []
if floder_path is None:
raise Exception("floder_path is None")
for dirpath, dirnames, filenames in os.walk(floder_path):
for name in filenames:
file_list.append(dirpath + '\\' + name)
return file_list
本回答被网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询