tempfile
— 生成临时文件和目录
¶
源代码: Lib/tempfile.py
此模块创建临时文件和目录。它工作于所有支持的平台。
TemporaryFile
,
NamedTemporaryFile
,
TemporaryDirectory
,和
SpooledTemporaryFile
are high-level interfaces which provide automatic cleanup and can be used as
context managers
.
mkstemp()
and
mkdtemp()
are lower-level functions which require manual cleanup.
All the user-callable functions and constructors take additional arguments which allow direct control over the location and name of temporary files and directories. Files names used by this module include a string of random characters which allows those files to be securely created in shared temporary directories. To maintain backward compatibility, the argument order is somewhat odd; it is recommended to use keyword arguments for clarity.
The module defines the following user-callable items:
- tempfile. TemporaryFile ( mode = 'w+b' , buffering = -1 , encoding = None , newline = None , suffix = None , prefix = None , dir = None , * , errors = None ) ¶
-
返回 像文件对象 that can be used as a temporary storage area. The file is created securely, using the same rules as
mkstemp(). It will be destroyed as soon as it is closed (including an implicit close when the object is garbage collected). Under Unix, the directory entry for the file is either not created at all or is removed immediately after the file is created. Other platforms do not support this; your code should not rely on a temporary file created using this function having or not having a visible name in the file system.The resulting object can be used as a 上下文管理器 (见 范例 ). On completion of the context or destruction of the file object the temporary file will be removed from the filesystem.
The mode parameter defaults to
'w+b'so that the file created can be read and written without being closed. Binary mode is used so that it behaves consistently on all platforms without regard for the data that is stored. buffering , encoding , errors and newline are interpreted as foropen().The dir , prefix and suffix parameters have the same meaning and defaults as with
mkstemp().The returned object is a true file object on POSIX platforms. On other platforms, it is a file-like object whose
fileattribute is the underlying true file object.The
os.O_TMPFILEflag is used if it is available and works (Linux-specific, requires Linux kernel 3.11 or later).On platforms that are neither Posix nor Cygwin, TemporaryFile is an alias for NamedTemporaryFile.
引发 审计事件
tempfile.mkstemp采用自变量fullpath.3.5 版改变: The
os.O_TMPFILE标志现被使用 (若可用)。3.8 版改变: 添加 errors 参数。