python - 在充满文件的目录中递归搜索特定字符串
问题描述
我有一个巨大的目录,有子目录和 txt 文件。我想在我的 dir/s 中递归搜索特定的字符串。如果我找到匹配项,我想打印完整路径和关键字。由于某种原因,我似乎无法if keyword in line
上班。(我知道“威廉姆斯”在我的文件中)
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")
解决方案
推荐阅读
- label - 将添加源中的点添加到 Mapbox 标签
- json - pySpark 从 json 文件转置数据帧并添加标题;
- python - 将列表格式化为字符串(与 ArcPy 的按属性函数选择兼容的字符串格式)
- reactjs - React native fetching GeoFire,flatlist 中只能显示一个数据
- c++ - C++推导的返回类型在定义之前不能使用
- javascript - 是否可以构造一个正则表达式来匹配具有千位和小数分隔符的数字,例如 1,000.00 和 1,000.00?
- java - 时间戳返回错误的日期并获得解析异常
- html - HTML 视频不适用于苹果设备(Chrome/Safari/etc)
- vba - 尝试在访问中执行 db.openrecordset 时出错
- regex - 突出显示包含无效数据的单元格