我正在做一些文件处理,为了生成文件,我需要从现有数据生成一些临时文件,然后使用该文件作为函数的输入.
但是我不明白我应该把那个文件保存在哪里,然后删除它.
是否有在用户会话后自动删除文件的临时位置
我正在做一些文件处理,为了生成文件,我需要从现有数据生成一些临时文件,然后使用该文件作为函数的输入.
但是我不明白我应该把那个文件保存在哪里,然后删除它.
是否有在用户会话后自动删除文件的临时位置
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