我有一个很大的目录,里面有子目录和txt文件。
我想递归地在目录中搜索特定的字符串。
如果我找到匹配项,我想打印完整路径和关键字。由于某些原因,我似乎无法if keyword in line
工作。 (我知道“ williams”在我的文件中)
import os
search_path = "/home/lasse/Desktop/DB1"
file_type = ".txt"
keyword = "williams"
if not (search_path.endswith("/") or search_path.endswith("\\")):
search_path = search_path + "/"
if not os.path.exists(search_path):
search_path = "."
print("Path dosn't exists")
for folder, dirs, files in os.walk(search_path):
for file in files:
if file.endswith(file_type):
fullpath = os.path.join(folder, file)
with open(fullpath, 'r') as my_file:
for line in my_file:
print("test")
if keyword in line:
print(fullpath, line, keyword)
else:
print("Cant find keyword keyword")