Created
August 7, 2022 14:27
-
-
Save chasemc/0b283e7debf30f88a04b6ff01420f3ca to your computer and use it in GitHub Desktop.
Download an NCBI genbank file for a subset of a nucleotide sequence
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import requests | |
from pathlib import Path | |
def dl_subsequence_gbk(outdir, accession, n_start, n_stop): | |
response = requests.post( | |
"https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi", | |
params={ | |
"db": "nuccore", | |
"rettype": "gb", | |
"from": str(n_start), | |
"to": str(n_stop), | |
}, | |
files={"id": accession}, | |
) | |
if not response.ok: | |
print(f"Failed with response: {response.reason}") | |
else: | |
try: | |
organism = [ | |
i.strip() | |
for i in response.text.split("\n") | |
if i.strip().startswith("ORGANISM") | |
][0] | |
organism = organism.removeprefix("ORGANISM") | |
organism = organism.strip() | |
organism = organism.replace(" ", "-") | |
except: | |
organism = "NA" | |
try: | |
assembly = [ | |
i.strip() | |
for i in response.text.split("\n") | |
if i.strip().startswith("Assembly") | |
][0] | |
assembly = assembly.removeprefix("Assembly:") | |
assembly = assembly.strip() | |
assembly = assembly.replace(" ", "_") | |
except: | |
assembly = "NA" | |
filepath = Path(outdir, f"{assembly}_{accession}_{organism}.gbk") | |
with open(filepath, "w") as file1: | |
file1.writelines(response.text) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Will result in the file:
/home/chase/Downloads/test/GCF_001077745.1_NZ_LFOD01000025.1_Mycolicibacterium-conceptionense.gbk