在csv python中编写for循环的输出

时间:2019-01-02 22:11:13

标签: python

我想写for循环的结果,它是PMID =文本ID,日期=发布日期,标题=文章标题,摘要=摘要在csv文件中,但是它仅保存输出的一个元素没有全部

  import numpy as np 
  from Bio import Entrez
  from Bio import Medline
  import csv
  import pandas as pd
  Entrez.email = "shayezkarimcide@gmail.com"

  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 个答案:

答案 0 :(得分:0)

您正在打开文件,然后在循环内写入和关闭文件(with确保在with的作用域完成后关闭文件),因此它将为循环中的每个元素替换先前的文件。

尝试在循环之前仅打开文件一次:

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)