首页 > 解决方案 > 在 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)

标签: python-3.x

解决方案


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() 方法将在调用时从文件中返回一行。


推荐阅读