## Split a PDB file into separate chains


import os, sys

fileName = sys.argv[1]
baseName = os.path.splitext(fileName)[0] # get filename without extension

# Read the lines from the input file that have 'HETATM' and 'NAD' in the 
# correct positions into a list:
with open(fileName) as f:
    linesNAD = [li for li in f if li.startswith("ATOM")]

# Build a set of the chains found in the lines we have read in:
chains = {li[21] for li in linesNAD if li[21] in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'}

# For each chain, create an output file and write the lines for that chain:
for chain in chains:
    outfileName = baseName + '_' + chain + '.pdb'
    with open(outfileName, 'w') as o:
        o.writelines([li for li in linesNAD if li[21] == chain])
