【问题标题】:Why python script has to be run twice?为什么python脚本必须运行两次?
【发布时间】:2015-04-22 02:44:42
【问题描述】:

我编写了这个 python 脚本来抓取网络数据并将输出打印到单独的文件中。 'refID.txt' 文件有一个 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  

我的问题是,要在“output.txt”文件中打印输出,代码必须运行两次。如果脚本运行一次,则不会打印任何输出。但是如果第二次运行代码,就会打印输出。 代码只运行一次如何打印输出?

【问题讨论】:

  • 你在调用 f.close() 吗?我不确定这一点,但我知道 XlsxWriter 在流关闭之前不会真正将数据写入文件。也许您的数据会保存在内存中,直到再次调用 open()?
  • 我没有。我必须这样做吗?
  • 我想试试看。
  • 我不确定print &gt;&gt; f, printing 是做什么的,但您是否尝试过将其换成f.write(printing)?与循环的每次迭代相比,只写入一次文件也更有效。
  • @Will - 我在最后添加了 f.close() 。它有效!谢谢!

标签: python input web-scraping output


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

    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 语句的更多信息。

    【讨论】:

    • 我会试试这个。谢谢!
    • 这不起作用。出现以下错误消息 - “警告:'with' 将成为 Python 2.6 中的保留关键字”
    • 您使用的是什么 python 版本。这是为了标准。 Python 2.7 及更高版本
    • 请更新到python2.7或更高版本。如果您更新到 python 3 及更高版本,您将不得不将您的打印语句更改为打印方法,例如 print()
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-01
    • 2022-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多