0

i want to write the result of for loop which is PMID = Id of litrature ,Date = date of publication ,title = title of article,Abstract = abtract of artilce in csv file but it is saving only one element of the output no all

  import numpy as np 
  from Bio import Entrez
  from Bio import Medline
  import csv
  import pandas as pd
  Entrez.email = "[email protected]"

  handle = Entrez.esearch(db="pmc", 
        term = "Antimicrobial resistance Drug Resistance",
        rettype = "medline",retmode = "txt",
        retmax= "200",sort = "pub date")

  result = Entrez.read(handle)

  handle.close()

  Id = result ['IdList']

  print (Id)

  handle2 = Entrez.efetch(db="pmc", 
    id=Id, rettype="medline", 
    retmode="text")

  records = Medline.parse(handle2)


  header = ['ID','Date','Title','Abstract']



  for result in records :

   PMID = result['PMID']
   Abstract = result['AB']
   title = result['TI']
   Date = result['DP']

   print (PMID,Date,title,Abstract)


   fields = [PMID, title,Date,Abstract]

   rows = [PMID,Date,title,Abstract]

   with open ('/home/shayez/Desktop/karim.csv','wt') as csvfile:
      writer = csv.writer(csvfile, delimiter ="\t" )
      writer.writerow(header)

      writer.writerow(rows)

  handle2.close()
1
  • Because you open the file in write mode in a loop, which wipes any contents from the previous loop. Open in append mode (though this will be really inefficient and you'll probably want to refactor the code to be able to use writerows and open the file only once) Commented Jan 2, 2019 at 22:17

1 Answer 1

1

You are opening the file, writing and closing it inside the loop (the with makes sure the file is closed after the with's scope is done) so it is replacing the previous file for each element in the loop.

Try opening the file only once, before the loop:

with open ('/home/shayez/Desktop/karim.csv','wt') as csvfile:
    writer = csv.writer(csvfile, delimiter ="\t" )
    writer.writerow(header)

    for result in records :
        PMID = result['PMID']
        Abstract = result['AB']
        title = result['TI']
        Date = result['DP']

        print (PMID,Date,title,Abstract)

        fields = [PMID, title,Date,Abstract]
        rows = [PMID,Date,title,Abstract]

        writer.writerow(rows)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.