This is a test version of Biostars. For the public version, visit https://www.biostars.org.
How to iterate esearch and efetch

Hi all,

I am new with Biopython :)

def fetchByQuery(query,days):
Entrez.email = "email" # must give NCBI an email address
searchHandle=Entrez.esearch(db="pubmed", reldate =single_date, term=query, usehistory="y")
searchResults=Entrez.read(searchHandle)
searchHandle.close()
webEnv=searchResults["WebEnv"]
queryKey=searchResults["QueryKey"]
batchSize=10
try:
    fetchHandle = Entrez.efetch(db="pubmed", retmax=10, retmode="xml", webenv=webEnv, query_key=queryKey)
    data=fetchHandle.read()
    fetchHandle.close()
    return data
except:
    return None

I have a list of years year = [2000, 2001, 2002 etc] A list of terms terms = [cancer, diabete, etc] I want to extract pubmed for every year since 2000 ( so I need to itrate ! then for every year, I iterate every term and print the result in XML

Can someone help me with iterations ?

software error

Thank you ! Now I want to write the output for each tuple ( year, term) in an xml format This is what I have done:

enteryears = range(2017, 2016, -1)
termList=["unmet ","needs""]  

 for year in years:
 for query in termList:
    xml_data=fetchByQuery(query,years)
    if xml_data==None: 
        print 80*"*"+"\n"
        print "This search returned no Pubmed Data"

    else:
        with open(query+'.txt',"w") as temp_file:
                temp_file.write(xml_data(query,years))
                temp_file.close()

The issues: 1- with open(query+'.txt',"w") as temp_file: I want to specify the year and term list in each title of the xml file. 2- The way I am writing the code it returns files with the query names without years and with the same content !

Thanks in advance

You wrote this as a new question. Why add this as an answer and then accept it? I'm moving it to a comment.

Sorry I am new in the forum :)

1 answer

like this?

years=[Year_Range]
terms=[Terms]
for year in years:
    for term in terms:
        Your_Fetch_Function(year, term)

Log in to answer this question.