Home > Software design >  Searching for 2 variables in several files
Searching for 2 variables in several files

Time:06-05

I'm trying to find 2 values in several textbased files. The code i have is:

def newbat():
query1 = "Dump/data/log/batterystats/newbatterystats*"
name1 = "plug=ac"
strt = "RESET"
dus = os.path.join(path, query1)
entries1 = glob.glob(dus, recursive=True)
for entry in entries1:
    with open(entry, 'r') as file:
        for line in file:
            if name1 in line:
                outs3 = os.path.join(path, 'newbatterystat.txt')
                sys.stdout = open(outs3, 'a')
                print(entry   '\n', line)

The name1 variable works. If I replace name1 to strt it works. I cannot find out how to use both variables, so the output file is: RESET:TIME: 01-01-1970 plug=ac

CodePudding user response:

I'm sure there are many ways to solve your problem, I would recommend you to use regex:

>>> import re
>>> text = 'RESET:TIME: 01-01-1970 plug=ac'
>>> re.findall('(RESET|plug=ac)', text)
['RESET', 'plug=ac']

CodePudding user response:

No need for regex really.

I would do something like this for each file you need to search in.

First example if both words has to be in the line. Second example if one word of a list of words has to be in line.

fruits = """1. orange, pear
2. banana, apple
3. pear, apple
4. apple, banana
5. banana, orange"""

fruits_split = fruits.split('\n')

print('First example:')
for line in fruits_split:
    if 'apple' in line and 'banana' in line:
        print(line)

my_fruits = ['apple', 'banana']
print('\nSecond example:')

for line in fruits_split:
    if any(x in line for x in my_fruits):
        print(line)

Output:

First example:
2. banana, apple
4. apple, banana

Second example:
2. banana, apple
3. pear, apple
4. apple, banana
5. banana, orange

  • Related