Python:如何写入文件并下载?

时间:2017-07-06 17:52:28

标签: python python-2.7 python-3.x file flask

我有基于烧瓶的网络服务,我尝试将结果下载到文件到用户的桌面(通过https)。

我试过了:

def write_results_to_file(results):
    with open('output', 'w') as f:
     f.write('\t'.join(results[1:]) + '\n')

当我点击ui中的导出按钮时,此方法被激活。

但我得到了:

<type 'exceptions.IOError'>: [Errno 13] Permission denied: 'output'
      args = (13, 'Permission denied')
      errno = 13
      filename = 'output'
      message = ''
      strerror = 'Permission denied' 

有人可以告诉我这里我做错了吗?

1 个答案:

答案 0 :(得分:2)

  

有人可以告诉我这里我做错了吗?

您发布的功能不是实际的Flask视图功能(app.route()),因此它不能完全清楚您的服务器在做什么。

这可能更接近您需要的代码:

@app.route("/get_results")
def get_results():
    tsv_plaintext = ''

    # I'm assuming 'results' is a 2D array
    for row in results:
        tsv_plaintext += '\t'.join(row)
        tsv_plaintext += '\n'

    return Response(
        tsv_plaintext,
        mimetype="text/tab-separated-values",
        headers={"Content-disposition":
                 "attachment; filename=results.tsv"})

(在Flask: Download a csv file on clicking a button的帮助下)