How to get taxonomic specific ids for kingdom, phylum, class, order, family, genus and species from taxid?
I'll copy/paste my answer from StackOverflow here also.

The following code:

import csv
from ete3 import NCBITaxa

ncbi = NCBITaxa()

def get_desired_ranks(taxid, desired_ranks):
    lineage = ncbi.get_lineage(taxid)
    lineage2ranks = ncbi.get_rank(lineage)
    ranks2lineage = dict((rank, taxid) for (taxid, rank) in lineage2ranks.items())
    return {'{}_id'.format(rank): ranks2lineage.get(rank, '&lt;not present&gt;') for rank in desired_ranks}

def main(taxids, desired_ranks, path):
    with open(path, 'w') as csvfile:
        fieldnames = ['{}_id'.format(rank) for rank in desired_ranks]
        writer = csv.DictWriter(csvfile, delimiter='\t', fieldnames=fieldnames)
        writer.writeheader()
        for taxid in taxids:
            writer.writerow(get_desired_ranks(taxid, desired_ranks))

if __name__ == '__main__':
    taxids = [1204725, 2162,  1300163, 420247]
    desired_ranks = ['kingdom', 'phylum', 'class', 'order', 'family', 'genus', 'species']
    path = 'taxids.csv'
    main(taxids, desired_ranks, path)


Produces a file that looks like this:

kingdom_id  phylum_id   class_id    order_id    family_id   genus_id    species_id
&lt;not present&gt;   28890   183925  2158    2159    2160    2162
&lt;not present&gt;   28890   183925  2158    2159    2160    2162
&lt;not present&gt;   28890   183925  2158    2159    2160    2162
&lt;not present&gt;   28890   183925  2158    2159    2172    2173