pythonif-statementstring-search

Search if all string in .txt


I am trying to run a program to look at a .txt file and if, else depending on the content

I thought would be

Searhterms = [A, B]
with('output.txt') as f:

    if ('A' and 'B') in f.read():
        print('mix')
    eLif ('A') in f.read:
        if ('B') not in f.read:
            print('ONLY A')
    elif ('B') in f.read():
        if ('A') not in f.read:
            print('ONLY B') 
    else:
        if ('A' and 'B') not in f.read:
            print('NO AB)

But if A and B present it works, but if only one it skips to the else. I am getting more confused about the longer I look at this.


Solution

  • You'd better use this:

    Searhterms = [A, B]  # not sure why you need this
    
    with('output.txt') as fin :  # nice name for the INPUT file, btw
        lines = fin.readlines()
    
    for line in lines :
        if ('A' in line) and ('B' in line):
            print('mix')
        eLif 'A' in line:  # nice uppercase 'L', will puzzle the python
            #if 'B' not in line:    # don't need this
            print('ONLY A')
        elif 'B' in line:
            #if 'A' not in line:    # don't need this
            print('ONLY B') 
        else:
            #if ('A' and 'B') not in f.read:   # this condition is not required
            print('NO AB')
    
    if len(lines) == 0 :
        print('empty file')