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

2024-09-24 22:28:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我编写了这个python脚本到web碎片数据,并将输出打印到一个单独的文件中。 的refID.txt文件必须从每个站点的ID列表中提取一个ID。输出将被打印到'输出.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  

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


Tags: 文件代码importretxt脚本idurl
2条回答

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

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

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

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()和引用文件.close(),我用with语句打开了两个文件。这是处理文件时的最佳做法,因为当文件超出范围时,它将自动关闭文件。有关with语句的详细信息,请参见here。在

相关问题 更多 >