Python Forum

Full Version: IF and list
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,

I couldn't find a similar question asked yet, so I am opening a new thread. If I missed an answer somewhere, I apologize.

I created a function that reads from a file and if it contains or doesn't contain certain keywords, it writes the line to a new file.

This is my code:

def edit_pdb(PDB):
    infile = open(PDB)
    new_file_name = PDB + "_new.txt"
    newopen = open(new_file_name, 'w')
    for line in infile :
        if 'ATOM' in line and "CB" not in line and "CD" not in line and "OG" not in line and "NE" not in line and "CZ" not in line and "NH" not in line and "OD" not in line and "REMARK" not in line:
            newopen.write(line)

    newopen.close()  
I have a list of all the elements that are supposed to be "not in line"
conditions = ["CB", "CG", "CD", "OG", "NE", "CZ", "NH", "OD", "REMARK"]
How can make it so that the IF statement read the conditions from this list.

Cheers,
Matic
There are several ways
if 'ATOM' in line and not any(x in line for x in conditions): ...
or using a regular expression
import re
pattern = re.compile('|'.join(re.escape(x) for x in conditions))
...
if 'ATOM' in line and not pattern.search(line): ...
Thanks, that worked.

I had something similar at the beginning but probably messed up the syntax somewhere.

Cheers,
Matic