KeyError when getting features from a genbank file with biopython with some accessions but not others
Good question.
feature.qualifiers is a dict, if the dict doesn't have that key it will throw a KeyError. The way your code works it expects feature.qualifiers to have 'gene' as a key every time feature.type == 'CDS'. However, it is possible to have feature.type == 'CDS' without a gene entry and in the case of AP019703.1 this comes up before you reach the gene acrA.
As simeple fix is to simply use get instead:
feature.qualifiers.get(&quot;gene&quot;,[])

Now returns a empty list if there is not key &quot;gene&quot;, which also satisfies the 'name in' part of your if statement.
If you get stuck on stuff like this use more print statements, break up your if statements and look at the whole file (example below) to understand the structure.
gi_genome = 'AP019703.1'
name = 'acrA'
Entrez.email = 'email'
handle = Entrez.efetch(db=&quot;nucleotide&quot;, id=gi_genome, rettype=&quot;gbwithparts&quot;, retmode=&quot;text&quot;)
record = SeqIO.read(handle, &quot;gb&quot;)
handle.close()
with open('AP019703.gb' ,'w') as fout:
    SeqIO.write(record, fout, 'genbank')