flask ValueError:对关闭的文件进行I / O操作

时间:2020-01-05 09:02:17

标签: python flask

我有一个代码,用于从网页抓取,并将抓取的数据保存在html文件中,并将其显示为其他页面。下面是代码

from flask import Flask, render_template,request from bs4 import
BeautifulSoup import urllib.request import sys,os app =
Flask(__name__) @app.route('/') def index():
    return render_template ('index.html')

@app.route('/result',methods = ['POST']) def result():    if
request.method == 'POST':
      result = request.form.get("search")
      link = "https://xyz.comindex?search="
      url = (link+result)
      print(url)
      try:
         page = urllib.request.urlopen(url)
         soup = BeautifulSoup(page, 'html.parser')
         test = soup.findAll('div', attrs={"class": "search-inner-wrapper"})
         sys.stdout = open("tests.html", "w")
         print(test)
         sys.stdout.close()
         return render_template("SearchResults.html", test=test)
      except:
         print("An error occured.")
      return render_template("test.html", test=test)


if __name__ == '__main__':
    app.run(use_reloader = True, debug = True)

我的问题是,这段代码可以很好地工作,但只运行一次,当我重新加载索引页面并执行搜索查询时,我得到了

ValueError:已关闭文件的I / O操作。

我无法解决此问题,因为我每次都必须使用单个文件,并且不希望结果附加现有代码。

1 个答案:

答案 0 :(得分:2)

您正在将sys.stdout重新定义为您打开的文件的文件句柄。使用其他名称,不要覆盖sys.stdout。并且不要关闭sys.stdout。可以关闭您创建的文件句柄。

打开并读取文件,打开并写入文件的示例:

bjb@blueeyes:~$ cat /tmp/infile.html
<html>
<head>
</head>
<body>
<div class="search-inner-wrapper">fleeble flobble</div>
</body>
</html>
bjb@blueeyes:~$ cat /tmp/file2.py
#!/usr/bin/env python3


with open('/tmp/infile.html', 'r') as infile:
    page = infile.readlines()

with open('/tmp/outfile.html', 'w') as ofd:
    ofd.write(''.join(page))


bjb@blueeyes:~$ /tmp/file2.py
bjb@blueeyes:~$ cat /tmp/outfile.html
<html>
<head>
</head>
<body>
<div class="search-inner-wrapper">fleeble flobble</div>
</body>
</html>

/tmp/file2.py的第一行只是说这是一个python脚本。

接下来的两行打开一个名为/tmp/infile.html的文件以进行读取,并声明一个变量“ infile”作为读取文件描述符。然后,/ tmp / infile.html中的所有行都被读入字符串列表。

当我们离开该“ with”块时,文件将为我们关闭。

然后在接下来的两行中,打开/tmp/outfile.html进行写入,并使用变量ofd(“输出文件描述符”)保存文件描述符。我们使用ofd将列表“页面”中的一系列行写入该文件。一旦我们离开第二个“ with”块,就为我们关闭了输出文件。然后程序退出...我的最后一条命令转储了/tmp/outfile.html的内容,您可以看到它与infile.html相同。

如果要打开和关闭文件而不使用带块文件,则可以:

infile = open('/tmp/infile.html', 'r')
page = infile.readlines()
infile.close()

ofd = open('/tmp/outfile.html', 'w')
ofd.write(''.join(page))
ofd.close()

希望可以在烧瓶脚本中工作...