Python - How to store a Search Result (list) in a variable?

Viewed 150

I am having trouble storing a list in a variable. I am new to python so I don't know if this is the way to do it. In the example below, I am searching for a string in textfiles in a certain directory. I like to store the search results in a variable.

I have this:

import os.path
import glob

rootDir = '/Volumes/audio/TRANSCRIBE/OUT'

os.chdir( rootDir )
for files in glob.glob( "*.txt" ):
    with open(files) as f:
        contents = f.read()
    if (re.search(r'\b'+ re.escape(searchPhrase) + r'\b', contents, re.IGNORECASE)):
        print( files )

The 'Search Result' Output:

FW_A01_2020-12-01_1812_C0003.txt
FW_A01_2020-12-01_1908_C0010.txt
FW_A01_2020-12-01_2204_C0032.txt
FW_A01_2020-12-09_0350_C0225.txt
FW_A01_2020-12-09_0352_C0226.txt
FW_A01_2020-12-09_0353_C0227.txt
FW_A01_2020-12-09_0353_C0228.txt

My Question: How do I store this search result in a variable?

I tried this:

searchResult = files

But that does not work.

2 Answers

You can add an empty list that you append each new result like this:

results = []
for files in glob.glob( "*.txt" ):
    with open(files) as f:
        contents = f.read()
    if (re.search(r'\b'+ re.escape(searchPhrase) + r'\b', contents, re.IGNORECASE)):
        results.append(files)

Try:

Make an array/list, and add them to the list with .append()

import os.path
import glob

results = []
rootDir = '/Volumes/audio/TRANSCRIBE/OUT'

os.chdir( rootDir )
for files in glob.glob( "*.txt" ):
    with open(files) as f:
        contents = f.read()
    if (re.search(r'\b'+ re.escape(searchPhrase) + r'\b', contents, re.IGNORECASE)):
        results.append(files)
        print( files )

Related