0

I just want to list the filename matching the multiline string

n=Mike
s=Tyson

Below code works, but is there a more pythonic way, like a grep instead of reading the content and iterating line by line?

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)
rodee
  • 3,233
  • 5
  • 34
  • 70
  • 1
    Looks good. If you want to check only the first 2 lines of the file, check file.readline() https://docs.python.org/3/tutorial/inputoutput.html#methods-of-file-objects – Sylvain May 26 '21 at 21:21

1 Answers1

0
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

This would just create a list , through which you have to iterate again, i dont think there is any other way then iterating. you have to somehow at least read, if u dont want to store, the data from the file. If you are working with bigger amount of data, creating a dictionary might be more efficient.

readlines() method will return all the lines in a file in the format of a list where each element is a line in the file.

readline() method will return a line from the file when called.

Aru
  • 352
  • 1
  • 11
  • 1
    This is not correct. `if n=‘Mike’` will be evaluated independently and will always be true. – jdaz May 26 '21 at 23:13
  • This doesn't look for `s=Tyson` followed by `n=Mike`, I will have many name and surname combinations in the file separated by 2 new lines, so should match the lines next to each other. e.g: `n=mike\ns=Tyson\n\nn=mike\ns=Johnson` – rodee May 27 '21 at 11:59
  • @rodee with that specification, you should maybe create a list, in which the structure is held but the lines are items in the list. i dont think there is another approach than iterating in this case. – Aru May 27 '21 at 13:10
  • @rodee https://stackoverflow.com/questions/4940032/how-to-search-for-a-string-in-text-files maybe you can try something from here? – Aru May 28 '21 at 13:25
  • @jdaz i rewrote it – Aru May 28 '21 at 13:26