python-3.x - 在 Python 中查找与多行字符串匹配的文件名
问题描述
我只想列出与多行字符串匹配的文件名
n=Mike
s=Tyson
下面的代码有效,但是有没有更 Pythonic 的方式,比如grep
不是读取内容并逐行迭代?
import glob
>>> for filepath in glob.iglob('**/*.txt', recursive=True):
with open(filepath) as file:
content = file.read()
match = re.search('n=Mike\ns=Tyson', content)
if match:
print(filepath)
解决方案
import glob
k = 'n=Mike'
p = 's=Tyson'
filepath = glob.iglob('**/*.txt',recursive=True)
for filepath in glob.iglob('**/*.txt', recursive=True):
f = filepath
x = open(filepath)
y = x.readlines()
z = []
for item in y:
z.append(item.strip())
found = k in z
if found and z[z.index(k)+1] == p:
print(filepath)
else:
print("Not found")
print(z) #gives the stripped list
这只会创建一个列表,您必须通过它再次迭代,我认为除了迭代之外没有其他方法。如果您不想存储,您至少必须以某种方式读取文件中的数据。如果您正在处理大量数据,则创建字典可能更有效。
readlines() 方法将以列表的格式返回文件中的所有行,其中每个元素都是文件中的一行。
readline() 方法将在调用时从文件中返回一行。
推荐阅读
- asp.net - 修改 default.aspx 时页面呈现不同
- c++ - std::getline 在函数内部不起作用
- python - 某些列的 pandas DataFrame 中位数
- reactjs - React 组件结构
- c++ - 无法使用其基础类型中的值初始化枚举
- javascript - Puppeteer 无法使用获取属性
- python - 将文件行读入由特定字符串分隔的列表(尖锐的“#”)
- ssh - Tmux 窗口大小锁定
- javascript - 函数中的参数“e”
- ruby-on-rails - 从设置 Stripe 帐户重定向到应用程序后,Rails/Devise 和“完成 401 未授权”