Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
IF and list
#1
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
Reply
#2
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): ...
MaticBroz likes this post
Reply
#3
Thanks, that worked.

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

Cheers,
Matic
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020