【发布时间】:2012-11-17 03:52:48
【问题描述】:
我正在处理一些文件,为了生成文件,我需要从现有数据中生成一些临时文件,然后将该文件用作我的函数的输入。
但我很困惑我应该在哪里保存该文件然后删除它。
用户会话后是否有任何临时位置可以自动删除文件
【问题讨论】:
我正在处理一些文件,为了生成文件,我需要从现有数据中生成一些临时文件,然后将该文件用作我的函数的输入。
但我很困惑我应该在哪里保存该文件然后删除它。
用户会话后是否有任何临时位置可以自动删除文件
【问题讨论】:
Python 有 tempfile module 正是为了这个目的。您无需担心文件的位置/删除,它适用于所有支持的平台。
临时文件分为三种:
tempfile.TemporaryFile - 只是基本的临时文件,tempfile.NamedTemporaryFile - "这个函数的操作和TemporaryFile() 完全一样,除了文件保证在文件系统中有一个可见的名称(在 Unix 上,目录条目没有取消链接)。可以检索该名称来自文件对象的名称属性。",tempfile.SpooledTemporaryFile - "这个函数的操作和TemporaryFile() 完全一样,除了数据在内存中假脱机直到文件大小超过max_size,或者直到文件的fileno() 方法被调用,此时内容写入磁盘,操作与TemporaryFile() 一样。",编辑:您要求的示例用法可能如下所示:
>>> with TemporaryFile() as f:
f.write('abcdefg')
f.seek(0) # go back to the beginning of the file
print(f.read())
abcdefg
【讨论】:
您应该使用来自tempfile 模块的东西。我认为它拥有你需要的一切。
【讨论】:
我要补充一点,Django 在 django.core.files.temp 中有一个内置的 NamedTemporaryFile 功能,建议 Windows 用户使用 tempfile 模块。这是因为 Django 版本利用了 Windows 中的 O_TEMPORARY 标志,它可以防止在没有提供与代码库 here 中解释的相同标志的情况下重新打开文件。
使用它看起来像:
from django.core.files.temp import NamedTemporaryFile
temp_file = NamedTemporaryFile(delete=True)
Here 是一个关于它和使用内存文件的不错的小教程,感谢 Mayank Jain。
【讨论】:
我刚刚添加了一些重要的更改:将 str 转换为字节和一个命令调用,以显示在给定路径时外部程序如何访问文件。
import os
from tempfile import NamedTemporaryFile
from subprocess import call
with NamedTemporaryFile(mode='w+b') as temp:
# Encode your text in order to write bytes
temp.write('abcdefg'.encode())
# put file buffer to offset=0
temp.seek(0)
# use the temp file
cmd = "cat "+ str(temp.name)
print(os.system(cmd))
【讨论】: