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

但是我不明白我应该把那个文件保存在哪里,然后删除它.

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

推荐答案

Python有tempfile module个用于此目的.您不必担心文件的位置/删除,它可以在所有受支持的平台上运行.

有三种类型的临时文件:

  • tempfile.TemporaryFile-仅基本临时文件,
  • tempfile.NamedTemporaryFile-"This function operates exactly as 101 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 101 does, except that data is spooled in memory until the file size exceeds 102, or until the file’s 103 method is called, at which point the contents are written to disk and operation proceeds as with 101.",

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

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

    
abcdefg

Django相关问答推荐

升级到4.2时,获取默认文件存储/存储是互斥的

Django中的判断约束

在/Contact-Agent/Get()返回的多个对象返回了多个属性--它返回了2

RDBMS多对多关系Django

如何在创建对象后立即运行一次代码?

如何在Django REST框架中管理序列化程序?

如何显示;Django认证系统;在模板中?

源自访问外键关系的模型方法 get_absolute_url 的 django 重复 SQL 查询

Django 表单字段必填和可选配置

EmailBackend 用于在 Django 中通过多个 SMTP 发送邮箱

CherryPy 与 Django

在 virtualenv Ubuntu 12.10 中使用 pip 安装 lxml 错误:command 'gcc' failed with exit status 4

URL命名空间的一个真实例子

如何在 twitter-bootstrap 模式窗口中插入 django 表单?

从基于类的通用视图中获取 request.session

Django - 来自 QuerySet 的唯一列表

在 Django 1.8 或更高版本中填充时出现Models aren't loaded yet"错误

django 模板列表变量中的最后一个元素

如何将 django csrf 令牌直接嵌入 HTML?

Django:如何将数据保存到 ManyToManyField?