如何在python中生成文件而不将其保存到磁盘?

Saš*_*aba 7 python csv django

我正在使用 Python 2.7 和 Django 1.7。

我的管理界面中有一个方法可以生成某种 csv 文件。

def generate_csv(args):
    ...
    #some code that generates a dictionary to be written as csv
    ....

    # this creates a directory and returns its filepath
    dirname = create_csv_dir('stock')

    csvpath = os.path.join(dirname, 'mycsv_file.csv')
    fieldnames = [#some field names]

    # this function creates the csv file in the directory shown by the csvpath
    newcsv(data, csvheader, csvpath, fieldnames)

    # this automatically starts a download from that directory
    return HttpResponseRedirect('/media/csv/stock/%s' % csvfile)
Run Code Online (Sandbox Code Playgroud)

总而言之,我创建了一个 csv 文件,将其保存在磁盘上的某个位置,然后将其 URL 传递给用户进行下载。

我在想是否所有这些都可以在不写入光盘的情况下完成。我在谷歌上搜索了一下,也许内容处理附件可能对我有帮助,但我有点迷失在文档中。

无论如何,如果有更简单的方法可以做到这一点,我很想知道。

Saš*_*aba 7

感谢@Ragora,您为我指明了正确的方向。

我重写了newcsv方法:

def newcsv(data, csvheader, fieldnames):
    """
    Create a new csv file that represents generated data.
    """
    csvrow = []
    new_csvfile = StringIO.StringIO()
    wr = csv.writer(new_csvfile, quoting=csv.QUOTE_ALL)
    wr.writerow(csvheader)
    wr = csv.DictWriter(new_csvfile, fieldnames = fieldnames)

    for key in data.keys():
        wr.writerow(data[key])

    return new_csvfile
Run Code Online (Sandbox Code Playgroud)

并在管理员中:

csvfile = newcsv(data, csvheader, fieldnames)

response = HttpResponse(csvfile.getvalue(), content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename=stock.csv'
return response
Run Code Online (Sandbox Code Playgroud)