python_從文件查找關鍵字


#1、寫一個函數,傳入一個路徑和一個關鍵字(關鍵字是文件內容),找到文件內容里面有這個關鍵字的文件

import os
def find_file(keywords,path='/Users/wym/Desktop/work/Besttest/筆記/day6'):
file_list = get_all_file(path)
for file in file_list:
if file.endswith('.py') or file.endswith('.txt'):
with open(file,'r',encoding='utf-8') as fr:
if keywords in fr.read():
print(file)
print('=='*20)
def get_all_file(path):
file_list = []
for cur_path, cur_dirs, cur_files in os.walk(path):
for name in cur_files:
file_list.append(os.path.join(cur_path,name))
return file_list
keywords = input("Please input the key words that you want to search:")
path = input("Please input the filepath:")
find_file(keywords,path)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM