为什么python脚本必须运行两次?

时间:2015-04-22 02:44:42

标签: python input web-scraping output

我将此python脚本编写为Web废料数据并将输出打印到单独的文件中。 ' refID.txt' file有一个ID列表,每个ID都必须从站点中提取数据。输出将打印到" output.txt'文件。 这是我的代码;

import urllib
import re

referencefile = open("refID.txt")

IDlist = referencefile.read()

refIDlist = IDlist.split("\n")

f = open("output.txt", 'w')

i=0
while i<len(refIDlist):
  url = "http://www.ncbi.nlm.nih.gov/clinvar/variation/"+refIDlist[i]
  htmlfile = urllib.urlopen(url)
  htmltext = htmlfile.read()
  regex = '<dt>Variant type:</dt><dd>(.+?)</dd>'
  pattern = re.compile(regex)
  Vtype = re.findall(pattern,htmltext)
  vt = Vtype[0]
  printing = "Variation type of " + refIDlist[i] + " is " + str(vt)
  print >> f, printing
  i+=1  

我的问题是,输出要打印在&quot; output.txt&#39;文件,代码必须运行两次。如果脚本运行一次,则不会输出任何输出。但如果代码第二次运行,则会打印输出。 当代码只运行一次时,如何打印输出?

2 个答案:

答案 0 :(得分:1)

尝试使用 with open('output.txt', 'w') as f:

然后是您要在打开的文件上运行的代码。这将自动关闭它。见https://docs.python.org/3/library/functions.html#open

答案 1 :(得分:1)

如果您要处理文件,您应该始终记得关闭文件以确保正确读取和写入数据,并确保释放资源。

import urllib
import re

with open("refID.txt", 'r') as referencefile:
    IDlist = referencefile.read()

refIDlist = IDlist.split("\n")

with open("output.txt", 'w') as f:
    i=0
    while i<len(refIDlist):
      url = "http://www.ncbi.nlm.nih.gov/clinvar/variation/"+refIDlist[i]
      htmlfile = urllib.urlopen(url)
      htmltext = htmlfile.read()
      regex = '<dt>Variant type:</dt><dd>(.+?)</dd>'
      pattern = re.compile(regex)
      Vtype = re.findall(pattern,htmltext)
      vt = Vtype[0]
      printing = "Variation type of " + refIDlist[i] + " is " + str(vt)
      print >> f, printing
      i+=1 

我没有编写f.close()和引用file.close(),而是使用with语句打开了两个文件。这是处理文件时的最佳做法,因为它会在文件超出范围时自动关闭文件。请参阅here以获取有关with语句的更多信息。