<p>I see 2 problems.</p>
<p>First, you need to check if the qualifier your are searching for exists in the given CDS feature.</p>
<p>Second, the qualifier holds more then just the string <code>PKS</code> for example <code>Domain: PKS_AT (537-846). E-value: 1.5e-98</code>.</p>
<p>You could modify your code like this:</p>
<pre><code>feature_type = &quot;CDS&quot;
feature_qualifier = &quot;NRPS_PKS&quot;
target = &quot;PKS&quot;

def has_pks_value(feature, qualifier, part):
    return any(part in target for target in feature.qualifiers[qualifier])

for record in SeqIO.parse(input_handle, &quot;genbank&quot;):
    for feature in record.features:
        if feature.type == feature_type and feature_qualifier in feature.qualifiers.keys() and has_pks_value(feature, feature_qualifier, target) and len(feature.qualifiers['translation'])==1:
            output_handle.write(f&quot;&gt;{record.description} {feature.location.start} {feature.location.end} {feature.location.strand} \n {SeqFeature(feature.location).extract(record.seq)}&quot;)
</code></pre>
<p>I've created some variables which for your string. This might prevent you from making some typos.</p>
<p>Also instead of a list comprehension, I just run over all features and checked with a single <code>if</code> statement if the asked qualifier exists and contains the given value.</p>
<p>I also changed the string formatting to f-string. But I think you should create the Fasta Files using the <code>SeqIO</code> module of Biopython.</p>
<p>As result I got 37 sequences</p>
<hr />
<p>Update - I added a missing method to check for the correct value of the qualifier</p>

CC BY-SA 4.0
2021-11-15T21:08:56.590Z
Thank you for your suggestions, But I god the following error now.  `output_handle.write(f">{record.description} {feature.location.start} {feature.location.end} {feature.location.strand} \n {SeqFeature(feature.location).extract(record.seq)}")
                                                                                                                                                                               ^
SyntaxError: invalid syntax`
 could you please Help, I recently started using python (last 3 days) just for this purpose only trying to make sense of resources available online.
ambika
CC BY-SA 4.0
2021-11-15T21:36:10.817Z
Could you try run it without the f-string part? Just use your original version for the file writing
Mr_Z
CC BY-SA 4.0
2021-11-15T23:15:38.447Z
It has another error ` output_handle.write(">%s %s\n%s\n" % (record.description, feature.location, seq_feature.qualifiers['translation'][0]))
NameError: name 'seq_feature' is not defined
`
ambika
CC BY-SA 4.0
2021-11-16T18:48:40.897Z
The variable `seq_feature` doesn't exist anymore. Use `feature` instead
Mr_Z
CC BY-SA 4.0
2021-11-15T20:16:24.613Z
2021-11-15T21:34:04.480Z
2021-11-15T21:34:04.480Z
Mr_Z
<p>I am trying to extract the protein sequence of specific genes from gene bank like format file obtained from antismash part of which looks like this</p>
<pre><code>LOCUS       scaffold_10            47160 bp    DNA     linear   UNK 01-JAN-1980
DEFINITION  scaffold_10.
ACCESSION   scaffold_10
VERSION     scaffold_10
KEYWORDS    .
SOURCE
  ORGANISM
            .
COMMENT     ##antiSMASH-Data-START##
            Version      :: 6.0.1-25e43a7(changed)
            Run date     :: 2021-11-05 17:39:45
            NOTE: This is a single cluster extracted from a larger record!
            Orig. start  :: 2049841
            Orig. end    :: 2097001
            ##antiSMASH-Data-END##
FEATURES             Location/Qualifiers
     protocluster    1..47160
                     /aStool=&quot;rule-based-clusters&quot;
                     /contig_edge=&quot;False&quot;
                     /core_location=&quot;join{[2069841:2070128](+),
                     [2070175:2070449](+), [2070507:2071973](+),
                     [2072023:2074178](+), [2074232:2074784](+),
                     [2074838:2077001](+)}&quot;
                     /cutoff=&quot;20000&quot;
                     /detection_rule=&quot;cds(PKS_AT and (PKS_KS or ene_KS or mod_KS
                     or hyb_KS or itr_KS or tra_KS))&quot;
                     /neighbourhood=&quot;20000&quot;
                     /product=&quot;T1PKS&quot;
                     /protocluster_number=&quot;1&quot;
                     /tool=&quot;antismash&quot;
     proto_core      join(20001..20287,20335..20608,20667..22132,22183..24337,
                     24392..24943,24998..27160)
                     /aStool=&quot;rule-based-clusters&quot;
                     /tool=&quot;antismash&quot;
                     /cutoff=&quot;20000&quot;
                     /detection_rule=&quot;cds(PKS_AT and (PKS_KS or ene_KS or mod_KS
                     or hyb_KS or itr_KS or tra_KS))&quot;
                     /neighbourhood=&quot;20000&quot;
                     /product=&quot;T1PKS&quot;
                     /protocluster_number=&quot;1&quot;
     cand_cluster    1..47160
                     /SMILES=&quot;CC(=O)C(=O)O&quot;
                     /candidate_cluster_number=&quot;1&quot;
                     /contig_edge=&quot;False&quot;
                     /detection_rules=&quot;cds(PKS_AT and (PKS_KS or ene_KS or
                     mod_KS or hyb_KS or itr_KS or tra_KS))&quot;
                     /kind=&quot;single&quot;
                     /product=&quot;T1PKS&quot;
                     /protoclusters=&quot;1&quot;
                     /tool=&quot;antismash&quot;
     region          1..47160
                     /candidate_cluster_numbers=&quot;1&quot;
                     /contig_edge=&quot;False&quot;
                     /product=&quot;T1PKS&quot;
                     /region_number=&quot;1&quot;
                     /rules=&quot;cds(PKS_AT and (PKS_KS or ene_KS or mod_KS or
                     hyb_KS or itr_KS or tra_KS))&quot;
                     /tool=&quot;antismash&quot;
     CDS             1899..2720
                     /ID=&quot;CDS_13110&quot;
                     /NRPS_PKS=&quot;Domain: PKS_KR (26-149). E-value: 7.6e-08.
                     Score: 24.2. Matches aSDomain:
                     nrpspksdomains_jgi.p_FusspF11_1_766668_PKS_KR.1&quot;
                     /NRPS_PKS=&quot;type: other&quot;
                     /gene=&quot;jgi.p_FusspF11_1_766668&quot;
                     /gene_functions=&quot;biosynthetic-additional (smcogs)
                     SMCOG1001:short-chain dehydrogenase/reductase SDR (Score:
                     161.6; E-value: 3.9e-49)&quot;
                     /gene_kind=&quot;biosynthetic-additional&quot;
                     /phase=&quot;0&quot;
                     /source=&quot;prediction&quot;
                     /transl_table=1
                     /translation=&quot;MTPPPKSALESDPAVGAQRRFSVTGNAVVTGGAGVLGLHACDALL
                     EHGLEGLMILDVNPAQSQGQITSLQNKFPRAKIMALKVDVTDENVVNAAMEETARVLGS
                     IDTLICFVGVVGCVETLDMPVPQWRKILDINTTGSFICAQAAARQMVKRGRGGSIVFVA
                     SISAHRVNYPQPQAAYNVSKSALLMLKSCLAAEWARYGIRTNSISPGYMDTILNEGDGI
                     AEHRKIWAEHNPSGRMGAPSELTGTVVLLASSAGSYINGADIVVDGGGIVL&quot;
     aSDomain        1977..2345
                     /aSDomain=&quot;PKS_KR&quot;
                     /aSTool=&quot;nrps_pks_domains&quot;
                     /database=&quot;nrpspksdomains.hmm&quot;
                     /detection=&quot;hmmscan&quot;
                     /domain_id=&quot;nrpspksdomains_jgi.p_FusspF11_1_766668_PKS_KR.1
                     &quot;
                     /evalue=&quot;7.60E-08&quot;
                     /label=&quot;jgi.p_FusspF11_1_766668_PKS_KR.1&quot;
                     /locus_tag=&quot;jgi.p_FusspF11_1_766668&quot;
                     /protein_end=&quot;149&quot;
                     /protein_start=&quot;26&quot;
                     /score=&quot;24.2&quot;
                     /specificity=&quot;KR activity: inactive&quot;
                     /specificity=&quot;KR stereochemistry: C1&quot;
                     /tool=&quot;antismash&quot;
                     /translation=&quot;AVVTGGAGVLGLHACDALLEHGLEGLMILDVNPAQSQGQITSLQN
                     KFPRAKIMALKVDVTDENVVNAAMEETARVLGSIDTLICFVGVVGCVETLDMPVPQWRK
                     ILDINTTGSFICAQAAARQ&quot;
     aSModule        1977..2345
                     /domains=&quot;nrpspksdomains_jgi.p_FusspF11_1_766668_PKS_KR.1&quot;
                     /incomplete
                     /locus_tags=&quot;jgi.p_FusspF11_1_766668&quot;
                     /tool=&quot;antismash&quot;
                     /type=&quot;pks&quot;
     CDS_motif       1980..2042
                     /aSTool=&quot;nrps_pks_domains&quot;
                     /database=&quot;abmotifs&quot;
                     /detection=&quot;hmmscan&quot;
                     /domain_id=&quot;nrpspksmotif_jgi.p_FusspF11_1_766668_0001&quot;
                     /evalue=&quot;1.90E-05&quot;
                     /label=&quot;PKSI-KR_m1&quot;
                     /locus_tag=&quot;jgi.p_FusspF11_1_766668&quot;
                     /protein_end=&quot;48&quot;
                     /protein_start=&quot;27&quot;
                     /score=&quot;17.3&quot;
                     /tool=&quot;antismash&quot;
                     /translation=&quot;VVTGGAGVLGLHACDALLEHG&quot;
     CDS             join(3252..3263,3321..3443,3493..4428)
                     /ID=&quot;CDS_13111&quot;
                     /NRPS_PKS=&quot;Domain: PKS_ER (28-277). E-value: 6.4e-13.
                     Score: 40.2. Matches aSDomain:
                     nrpspksdomains_jgi.p_FusspF11_1_794272_PKS_ER.1&quot;
                     /NRPS_PKS=&quot;type: other&quot;
                     /gene=&quot;jgi.p_FusspF11_1_794272&quot;
                     /gene_functions=&quot;biosynthetic-additional (smcogs)
                     SMCOG1040:alcohol dehydrogenase (Score: 275.7; E-value:
                     7.6e-84)&quot;
                     /gene_kind=&quot;biosynthetic-additional&quot;
                     /phase=&quot;0&quot;
                     /source=&quot;prediction&quot;
                     /transl_table=1
                     /translation=&quot;MSQTNLSCVLYGPGKARFENRPVPSLKDAHDVIIRISYVGVCGSD
                     VHFWTDGGFARKVSEDQPLVMGHEASGIVRSIGPDVTLLKPGDRVAIEPGFSCRRCKQC
                     KDGRYNLCPKMKFAADPPLTQGTLSRFFSIPEDFAYKIPDSLSLEEAVLVEPLAVAVHG
                     IRLAGLEVGQRVLVQGSGTIGLLTAAVAKAYGAKQVYITDVNLDKIKFAKKYLECSAFI
                     PDLGSTPEENAARFKTETGLDDGVDAVIECTGVEASTQTGLLALSAGGVLVQVGLGKPV
                     QAIPIHAMSEKEIVLKTSFRYGPGDYEIALELLESGKVSVRPLISSITPFEKATEAWEK
                     TRKGKGIKNLIRGVQD&quot;
</code></pre>
<p>Now from this I want to extract the protein sequence of gens having PKS domain (PKS_ER/PKS_AT/PKS_KS ...). So far I have tried the following biopython code but it is giving me error</p>
<pre><code>from Bio import SeqIO
from Bio.SeqFeature import SeqFeature

gbk = &quot;myfile_predicted_SMclusters.gbk&quot;
fa = &quot;myfile_PKS_protein.fa&quot;
input_handle = open(gbk, &quot;r&quot;)
output_handle = open(fa, &quot;w&quot;)

for record in SeqIO.parse(input_handle, &quot;genbank&quot;):
    features = [feature for feature in record.features if feature.type == &quot;CDS&quot;]
    for feature in features:
        if feature.qualifiers[&quot;NRPS_PKS&quot;][1] == &quot;PKS&quot;:
        assert len(seq_feature.qualifiers['translation'])==1
        output_handle.write(&quot;&gt;%s %s\n%s\n&quot; % (
            record.description,
            feature.location,
            seq_feature.qualifiers['translation'][0]))

output_handle.close()
input_handle.close()
</code></pre>
<p>The error is as follows:</p>
<pre><code>if feature.qualifiers[&quot;NRPS_PKS&quot;][1] == &quot;PKS&quot;:
KeyError: 'NRPS_PKS'
</code></pre>
<p>The link to the sample inputfile is below:
<a href="https://antismash.secondarymetabolites.org/upload/bacteria-ab76f3b0-768f-495c-beb0-885651eb2439/Necha_masked_scaffolds.gbk" rel="nofollow noreferrer">sample my_file.gbk</a></p>
<p>I'm using python 3.8.8</p>
<p>Please help!!!</p>

<python>
Error while parsing gene bank file using Biopython
# Error while parsing gene bank file using Biopython

(Asked by: username_0 on 2021-11-15)

I am trying to extract the protein sequence of specific genes from gene bank like format file obtained from antismash part of which looks like this
LOCUS       scaffold_10            47160 bp    DNA     linear   UNK 01-JAN-1980
DEFINITION  scaffold_10.
ACCESSION   scaffold_10
VERSION     scaffold_10
KEYWORDS    .
SOURCE
  ORGANISM
            .
COMMENT     ##antiSMASH-Data-START##
            Version      :: 6.0.1-25e43a7(changed)
            Run date     :: 2021-11-05 17:39:45
            NOTE: This is a single cluster extracted from a larger record!
            Orig. start  :: 2049841
            Orig. end    :: 2097001
            ##antiSMASH-Data-END##
FEATURES             Location/Qualifiers
     protocluster    1..47160
                     /aStool="rule-based-clusters"
                     /contig_edge="False"
                     /core_location="join{[2069841:2070128](+),
                     [2070175:2070449](+), [2070507:2071973](+),
                     [2072023:2074178](+), [2074232:2074784](+),
                     [2074838:2077001](+)}"
                     /cutoff="20000"
                     /detection_rule="cds(PKS_AT and (PKS_KS or ene_KS or mod_KS
                     or hyb_KS or itr_KS or tra_KS))"
                     /neighbourhood="20000"
                     /product="T1PKS"
                     /protocluster_number="1"
                     /tool="antismash"
     proto_core      join(20001..20287,20335..20608,20667..22132,22183..24337,
                     24392..24943,24998..27160)
                     /aStool="rule-based-clusters"
                     /tool="antismash"
                     /cutoff="20000"
                     /detection_rule="cds(PKS_AT and (PKS_KS or ene_KS or mod_KS
                     or hyb_KS or itr_KS or tra_KS))"
                     /neighbourhood="20000"
                     /product="T1PKS"
                     /protocluster_number="1"
     cand_cluster    1..47160
                     /SMILES="CC(=O)C(=O)O"
                     /candidate_cluster_number="1"
                     /contig_edge="False"
                     /detection_rules="cds(PKS_AT and (PKS_KS or ene_KS or
                     mod_KS or hyb_KS or itr_KS or tra_KS))"
                     /kind="single"
                     /product="T1PKS"
                     /protoclusters="1"
                     /tool="antismash"
     region          1..47160
                     /candidate_cluster_numbers="1"
                     /contig_edge="False"
                     /product="T1PKS"
                     /region_number="1"
                     /rules="cds(PKS_AT and (PKS_KS or ene_KS or mod_KS or
                     hyb_KS or itr_KS or tra_KS))"
                     /tool="antismash"
     CDS             1899..2720
                     /ID="CDS_13110"
                     /NRPS_PKS="Domain: PKS_KR (26-149). E-value: 7.6e-08.
                     Score: 24.2. Matches aSDomain:
                     nrpspksdomains_jgi.p_FusspF11_1_766668_PKS_KR.1"
                     /NRPS_PKS="type: other"
                     /gene="jgi.p_FusspF11_1_766668"
                     /gene_functions="biosynthetic-additional (smcogs)
                     SMCOG1001:short-chain dehydrogenase/reductase SDR (Score:
                     161.6; E-value: 3.9e-49)"
                     /gene_kind="biosynthetic-additional"
                     /phase="0"
                     /source="prediction"
                     /transl_table=1
                     /translation="MTPPPKSALESDPAVGAQRRFSVTGNAVVTGGAGVLGLHACDALL
                     EHGLEGLMILDVNPAQSQGQITSLQNKFPRAKIMALKVDVTDENVVNAAMEETARVLGS
                     IDTLICFVGVVGCVETLDMPVPQWRKILDINTTGSFICAQAAARQMVKRGRGGSIVFVA
                     SISAHRVNYPQPQAAYNVSKSALLMLKSCLAAEWARYGIRTNSISPGYMDTILNEGDGI
                     AEHRKIWAEHNPSGRMGAPSELTGTVVLLASSAGSYINGADIVVDGGGIVL"
     aSDomain        1977..2345
                     /aSDomain="PKS_KR"
                     /aSTool="nrps_pks_domains"
                     /database="nrpspksdomains.hmm"
                     /detection="hmmscan"
                     /domain_id="nrpspksdomains_jgi.p_FusspF11_1_766668_PKS_KR.1
                     "
                     /evalue="7.60E-08"
                     /label="jgi.p_FusspF11_1_766668_PKS_KR.1"
                     /locus_tag="jgi.p_FusspF11_1_766668"
                     /protein_end="149"
                     /protein_start="26"
                     /score="24.2"
                     /specificity="KR activity: inactive"
                     /specificity="KR stereochemistry: C1"
                     /tool="antismash"
                     /translation="AVVTGGAGVLGLHACDALLEHGLEGLMILDVNPAQSQGQITSLQN
                     KFPRAKIMALKVDVTDENVVNAAMEETARVLGSIDTLICFVGVVGCVETLDMPVPQWRK
                     ILDINTTGSFICAQAAARQ"
     aSModule        1977..2345
                     /domains="nrpspksdomains_jgi.p_FusspF11_1_766668_PKS_KR.1"
                     /incomplete
                     /locus_tags="jgi.p_FusspF11_1_766668"
                     /tool="antismash"
                     /type="pks"
     CDS_motif       1980..2042
                     /aSTool="nrps_pks_domains"
                     /database="abmotifs"
                     /detection="hmmscan"
                     /domain_id="nrpspksmotif_jgi.p_FusspF11_1_766668_0001"
                     /evalue="1.90E-05"
                     /label="PKSI-KR_m1"
                     /locus_tag="jgi.p_FusspF11_1_766668"
                     /protein_end="48"
                     /protein_start="27"
                     /score="17.3"
                     /tool="antismash"
                     /translation="VVTGGAGVLGLHACDALLEHG"
     CDS             join(3252..3263,3321..3443,3493..4428)
                     /ID="CDS_13111"
                     /NRPS_PKS="Domain: PKS_ER (28-277). E-value: 6.4e-13.
                     Score: 40.2. Matches aSDomain:
                     nrpspksdomains_jgi.p_FusspF11_1_794272_PKS_ER.1"
                     /NRPS_PKS="type: other"
                     /gene="jgi.p_FusspF11_1_794272"
                     /gene_functions="biosynthetic-additional (smcogs)
                     SMCOG1040:alcohol dehydrogenase (Score: 275.7; E-value:
                     7.6e-84)"
                     /gene_kind="biosynthetic-additional"
                     /phase="0"
                     /source="prediction"
                     /transl_table=1
                     /translation="MSQTNLSCVLYGPGKARFENRPVPSLKDAHDVIIRISYVGVCGSD
                     VHFWTDGGFARKVSEDQPLVMGHEASGIVRSIGPDVTLLKPGDRVAIEPGFSCRRCKQC
                     KDGRYNLCPKMKFAADPPLTQGTLSRFFSIPEDFAYKIPDSLSLEEAVLVEPLAVAVHG
                     IRLAGLEVGQRVLVQGSGTIGLLTAAVAKAYGAKQVYITDVNLDKIKFAKKYLECSAFI
                     PDLGSTPEENAARFKTETGLDDGVDAVIECTGVEASTQTGLLALSAGGVLVQVGLGKPV
                     QAIPIHAMSEKEIVLKTSFRYGPGDYEIALELLESGKVSVRPLISSITPFEKATEAWEK
                     TRKGKGIKNLIRGVQD"

Now from this I want to extract the protein sequence of gens having PKS domain (PKS_ER/PKS_AT/PKS_KS ...). So far I have tried the following biopython code but it is giving me error
from Bio import SeqIO
from Bio.SeqFeature import SeqFeature

gbk = "myfile_predicted_SMclusters.gbk"
fa = "myfile_PKS_protein.fa"
input_handle = open(gbk, "r")
output_handle = open(fa, "w")

for record in SeqIO.parse(input_handle, "genbank"):
    features = [feature for feature in record.features if feature.type == "CDS"]
    for feature in features:
        if feature.qualifiers["NRPS_PKS"][1] == "PKS":
        assert len(seq_feature.qualifiers['translation'])==1
        output_handle.write(">%s %s\n%s\n" % (
            record.description,
            feature.location,
            seq_feature.qualifiers['translation'][0]))

output_handle.close()
input_handle.close()

The error is as follows:
if feature.qualifiers["NRPS_PKS"][1] == "PKS":
KeyError: 'NRPS_PKS'

The link to the sample inputfile is below:
sample my_file.gbk
I'm using python 3.8.8
Please help!!!

**Tags:** python

---

## 1 answers

### Answer by username_1 on 2021-11-15. Score: 1

I see 2 problems.
First, you need to check if the qualifier your are searching for exists in the given CDS feature.
Second, the qualifier holds more then just the string PKS for example Domain: PKS_AT (537-846). E-value: 1.5e-98.
You could modify your code like this:
feature_type = "CDS"
feature_qualifier = "NRPS_PKS"
target = "PKS"

def has_pks_value(feature, qualifier, part):
    return any(part in target for target in feature.qualifiers[qualifier])

for record in SeqIO.parse(input_handle, "genbank"):
    for feature in record.features:
        if feature.type == feature_type and feature_qualifier in feature.qualifiers.keys() and has_pks_value(feature, feature_qualifier, target) and len(feature.qualifiers['translation'])==1:
            output_handle.write(f">{record.description} {feature.location.start} {feature.location.end} {feature.location.strand} \n {SeqFeature(feature.location).extract(record.seq)}")

I've created some variables which for your string. This might prevent you from making some typos.
Also instead of a list comprehension, I just run over all features and checked with a single if statement if the asked qualifier exists and contains the given value.
I also changed the string formatting to f-string. But I think you should create the Fasta Files using the SeqIO module of Biopython.
As result I got 37 sequences

Update - I added a missing method to check for the correct value of the qualifier

> **Comments:**
> **username_0**: Thank you for your suggestions, But I god the following error now.  `output_handle.write(f">{record.description} {feature.location.start} {feature.location.end} {feature.location.strand} \n {SeqFeature(feature.location).extract(record.seq)}")                                                                                                                                                                                ^ SyntaxError: invalid syntax`  could you please Help, I recently started using python (last 3 days) just for this purpose only trying to make sense of resources available online.  
> **username_1**: Could you try run it without the f-string part? Just use your original version for the file writing  
> **username_0**: It has another error ` output_handle.write(">%s %s\n%s\n" % (record.description, feature.location, seq_feature.qualifiers['translation'][0])) NameError: name 'seq_feature' is not defined `  
> **username_1**: The variable `seq_feature` doesn't exist anymore. Use `feature` instead  

---

