如何在django中生成临时文件然后销毁 [英] How to generate temporary file in django and then destroy

查看:389
本文介绍了如何在django中生成临时文件然后销毁的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一些文件处理和生成文件,我需要从现有数据生成一些临时文件,然后使用该文件作为我的功能的输入。

I am doing some file processing and for generating the file i need to generate some temporary file from existing data and then use that file as input to my function.

但是我很困惑我应该在哪里保存该文件然后删除它。

But i am confused where should i save that file and then delete it.

是否有任何临时位置文件在用户会话后自动删除

Is there any temp location where files automatically gets deleted after user session

推荐答案

Python具有 tempfile模块完全是为了这个目的。您不需要担心文件的位置/删除,它适用于所有支持的平台。

Python has tempfile module for exactly this purpose. You do not need to worry about the location/deletion of the file, it works on all supported platforms.

有三种类型的临时文件:

There are three types of temporary files:


  • tempfile.TemporaryFile - 只是基本的临时文件,

  • tempfile.NamedTemporaryFile - 此功能与 TemporaryFile()完全相同,但文件保证在文件系统中有一个可见的名称(在Unix上,目录条目不被取消链接),该名称可以从文件对象的name属性中检索。

  • tempfile.SpooledTemporaryFile - 此功能与 TemporaryFile()完全相同,只是数据是在内存中假脱机,直到文件大小超过 max_size ,或直到调用文件的 fileno()方法为止内容写入磁盘,操作按照 TemporaryFile()

  • tempfile.TemporaryFile - just basic temporary file,
  • tempfile.NamedTemporaryFile - "This function operates exactly as TemporaryFile() does, except that the file is guaranteed to have a visible name in the file system (on Unix, the directory entry is not unlinked). That name can be retrieved from the name attribute of the file object.",
  • tempfile.SpooledTemporaryFile - "This function operates exactly as TemporaryFile() does, except that data is spooled in memory until the file size exceeds max_size, or until the file’s fileno() method is called, at which point the contents are written to disk and operation proceeds as with TemporaryFile().",

编辑:您要求的示例用法可能如下所示:

EDIT: The example usage you asked for could look like this:

>>> with TemporaryFile() as f:
        f.write('abcdefg')
        f.seek(0)  # go back to the beginning of the file
        print(f.read())


abcdefg

这篇关于如何在django中生成临时文件然后销毁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆