tempfile
— Generate temporary files and directories生成临时文件和目录¶
Source code: Lib/tempfile.py
This module creates temporary files and directories. 此模块创建临时文件和目录。It works on all supported platforms. 它可以在所有受支持的平台上工作。TemporaryFile
, NamedTemporaryFile
, TemporaryDirectory
, and SpooledTemporaryFile
are high-level interfaces which provide automatic cleanup and can be used as context managers. TemporaryFile
、NamedTemporaryFile
、TemporaryDirectory
和SpooledTemporaryFile
是提供自动清理的高级接口,可以用作上下文管理器。mkstemp()
and mkdtemp()
are lower-level functions which require manual cleanup.mkstemp()
和mkdtemp()
是需要手动清理的低级函数。
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)¶ Return a file-like object that can be used as a temporary storage area.返回一个类似文件的对象,该对象可以用作临时存储区。The file is created securely, using the same rules as该文件是使用与mkstemp()
.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.在Unix下,文件的目录项要么根本不创建,要么在创建文件后立即删除。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 context manager (see Examples).生成的对象可以用作上下文管理器(参见示例)。On completion of the context or destruction of the file object the temporary file will be removed from the filesystem.在完成上下文或文件对象的销毁后,临时文件将从文件系统中删除。The mode parameter defaults tomode参数默认为'w+b'
so that the file created can be read and written without being closed.'w+b'
,因此创建的文件可以在不关闭的情况下读写。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 forbuffering、encoding、errors和newline被解释为open()
.open()
。The dir, prefix and suffix parameters have the same meaning and defaults as withdir、prefix和suffix参数的含义和默认值与mkstemp()
.mkstemp()
相同。The returned object is a true file object on POSIX platforms.返回的对象是POSIX平台上的true
file对象。On other platforms, it is a file-like object whose在其他平台上,它是一个类似file
attribute is the underlying true file object.file
的对象,其文件属性是底层的true
file对象。The如果os.O_TMPFILE
flag is used if it is available and works (Linux-specific, requires Linux kernel 3.11 or later).os.O_TMPFILE
标志可用且有效,则使用它(特定于Linux,需要Linux内核3.11或更高版本)。On platforms that are neither Posix nor Cygwin, TemporaryFile is an alias for NamedTemporaryFile.在既不是Posix也不是Cygwin的平台上,临时文件是NamedTemporaryFile的别名。Raises an auditing event使用参数tempfile.mkstemp
with argumentfullpath
.fullpath
引发审核事件tempfile.mkstemp
。Changed in version 3.5:版本3.5中更改:The如果可用,现在使用os.O_TMPFILE
flag is now used if available.os.O_TMPFILE
标志。Changed in version 3.8:版本3.8中更改:Added errors parameter.添加了errors参数。
-
tempfile.
NamedTemporaryFile
(mode='w+b', buffering=- 1, encoding=None, newline=None, suffix=None, prefix=None, dir=None, delete=True, *, errors=None)¶ 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).TemporaryFile()
完全相同,只是保证文件在文件系统中有一个可见的名称(在Unix上,目录条目没有取消链接)。That name can be retrieved from the可以从返回的类文件对象的name
attribute of the returned file-like object.name
属性中检索该名称。Whether the name can be used to open the file a second time, while the named temporary file is still open, varies across platforms (it can be so used on Unix; it cannot on Windows NT or later).在命名的临时文件仍处于打开状态时,是否可以使用该名称再次打开该文件,因平台而异(在Unix上可以这样使用;在Windows NT或更高版本上不能这样使用)。If delete is true (the default), the file is deleted as soon as it is closed.如果delete为true
(默认值),则文件在关闭后立即删除。The returned object is always a file-like object whose返回的对象始终是类似文件的对象,其file
attribute is the underlying true file object.file
属性是底层的真实文件对象。This file-like object can be used in a这个类似文件的对象可以在with语句中使用,就像普通文件一样。with
statement, just like a normal file.Raises an auditing event使用参数fullpath引发审核事件tempfile.mkstemp
with argumentfullpath
.tempfile.mkstemp
。Changed in version 3.8:版本3.8中更改: Added errors parameter.
-
class
tempfile.
SpooledTemporaryFile
(max_size=0, mode='w+b', buffering=- 1, encoding=None, newline=None, suffix=None, prefix=None, dir=None, *, errors=None)¶ This class operates exactly as该类的操作与TemporaryFile()
does, except that data is spooled in memory until the file size exceeds max_size, or until the file’sfileno()
method is called, at which point the contents are written to disk and operation proceeds as withTemporaryFile()
.TemporaryFile()
完全相同,只是数据在内存中后台处理,直到文件大小超过max_size,或者直到调用文件的fileno()
方法,此时内容被写入磁盘,操作与TemporaryFile()
一样进行。The resulting file has one additional method,生成的文件有一个附加方法rollover()
, which causes the file to roll over to an on-disk file regardless of its size.rollover()
,该方法使文件滚动到磁盘上的文件,而不管其大小。The returned object is a file-like object whose返回的对象是一个类似文件的对象,其_file
attribute is either anio.BytesIO
orio.TextIOWrapper
object (depending on whether binary or text mode was specified) or a true file object, depending on whetherrollover()
has been called._file
属性是io.BytesIO
或io.TextIOWrapper
对象(取决于是否指定了二进制或文本模式)或真实文件对象,取决于是否调用了rollover()
。This file-like object can be used in a这个类似文件的对象可以在with
statement, just like a normal file.with
语句中使用,就像普通文件一样。Changed in version 3.3:版本3.3中更改:the truncate method now accepts a截断方法现在接受size
argument.size
参数。Changed in version 3.8:版本3.8中更改:Added errors parameter.添加了errors参数。
-
class
tempfile.
TemporaryDirectory
(suffix=None, prefix=None, dir=None, ignore_cleanup_errors=False)¶ This class securely creates a temporary directory using the same rules as此类使用与mkdtemp()
.mkdtemp()
相同的规则安全地创建临时目录。The resulting object can be used as a context manager (see Examples).生成的对象可以用作上下文管理器(参见示例)。On completion of the context or destruction of the temporary directory object, the newly created temporary directory and all its contents are removed from the filesystem.在完成上下文或临时目录对象的销毁后,新创建的临时目录及其所有内容将从文件系统中删除。The directory name can be retrieved from the可以从返回对象的name
attribute of the returned object.name
属性中检索目录名。When the returned object is used as a context manager, the当返回的对象用作上下文管理器时,name
will be assigned to the target of theas
clause in thewith
statement, if there is one.name
将被分配给with
语句中as
子句的目标(如果有)。The directory can be explicitly cleaned up by calling the可以通过调用cleanup()
method.cleanup()
方法显式清理目录。If ignore_cleanup_errors is true, any unhandled exceptions during explicit or implicit cleanup (such as a如果ignore_cleanup_errors为PermissionError
removing open files on Windows) will be ignored, and the remaining removable items deleted on a “best-effort” basis.true
,则将忽略显式或隐式清理过程中任何未处理的异常(例如在Windows上删除打开的文件时发生的PermissionError),并尽最大努力删除剩余的可移动项。Otherwise, errors will be raised in whatever context cleanup occurs (the否则,无论发生什么上下文清理,都会引发错误(cleanup()
call, exiting the context manager, when the object is garbage-collected or during interpreter shutdown).cleanup()
调用,在垃圾收集对象时或在解释器关闭期间退出上下文管理器)。Raises an auditing event使用参数tempfile.mkdtemp
with argumentfullpath
.fullpath
引发审核事件tempfile.mkdtemp
。New in version 3.2.版本3.2中新增。Changed in version 3.10:版本3.10中更改:Added ignore_cleanup_errors parameter.添加了ignore_cleanup_errors参数。
-
tempfile.
mkstemp
(suffix=None, prefix=None, dir=None, text=False)¶ Creates a temporary file in the most secure manner possible.以尽可能安全的方式创建临时文件。There are no race conditions in the file’s creation, assuming that the platform properly implements the假设平台正确实现了os.O_EXCL
flag foros.open()
.os.open()
的os.O_EXCL
标志,则文件的创建中没有竞争条件。The file is readable and writable only by the creating user ID.文件只能通过创建用户ID进行读写。If the platform uses permission bits to indicate whether a file is executable, the file is executable by no one.如果平台使用权限位指示文件是否可执行,则该文件不可由任何人执行。The file descriptor is not inherited by child processes.子进程不会继承文件描述符。Unlike与TemporaryFile()
, the user ofmkstemp()
is responsible for deleting the temporary file when done with it.TemporaryFile()
不同,mkstemp()
的用户负责删除临时文件。If suffix is not如果suffix不是None
, the file name will end with that suffix, otherwise there will be no suffix.None
,则文件名将以该后缀结尾,否则将没有后缀。mkstemp()
does not put a dot between the file name and the suffix; if you need one, put it at the beginning of suffix.mkstemp()
不会在文件名和后缀之间加一个点;如果你需要,把它放在suffix的开头。If prefix is not如果prefix不是None
, the file name will begin with that prefix; otherwise, a default prefix is used.None
,则文件名将以该前缀开头;否则,将使用默认前缀。The default is the return value of默认值是gettempprefix()
orgettempprefixb()
, as appropriate.gettempprefix()
或gettempprefixb()
的返回值(视情况而定)。If dir is not如果dir不是None
, the file will be created in that directory; otherwise, a default directory is used.None
,则将在该目录中创建文件;否则,将使用默认目录。The default directory is chosen from a platform-dependent list, but the user of the application can control the directory location by setting the TMPDIR, TEMP or TMP environment variables.默认目录是从平台相关列表中选择的,但应用程序的用户可以通过设置TMPDIR、TEMP或TMP环境变量来控制目录位置。There is thus no guarantee that the generated filename will have any nice properties, such as not requiring quoting when passed to external commands via因此,无法保证生成的文件名具有任何良好的属性,例如通过os.popen()
.os.popen()
传递到外部命令时不需要引号。If any of suffix, prefix, and dir are not如果suffix、prefix和dir中的任何一个不是None
, they must be the same type.None
,则它们必须是相同的类型。If they are bytes, the returned name will be bytes instead of str.如果它们是字节,则返回的名称将是字节而不是str。If you want to force a bytes return value with otherwise default behavior, pass如果您想强制一个字节返回值具有其他默认行为,请传递suffix=b''
.suffix=b''
。If text is specified and true, the file is opened in text mode.如果指定了text并为true
,则文件将以文本模式打开。Otherwise, (the default) the file is opened in binary mode.否则,(默认)文件以二进制模式打开。mkstemp()
returns a tuple containing an OS-level handle to an open file (as would be returned by返回一个元组,该元组包含打开文件的操作系统级句柄(由os.open()
) and the absolute pathname of that file, in that order.os.open()
返回)和该文件的绝对路径名。Raises an auditing event使用参数tempfile.mkstemp
with argumentfullpath
.fullpath
引发审核事件tempfile.mkstemp
。Changed in version 3.5:版本3.5中更改:suffix, prefix, and dir may now be supplied in bytes in order to obtain a bytes return value.suffix、prefix和dir现在可以以字节为单位提供,以获得字节返回值。Prior to this, only str was allowed.在此之前,只允许str。suffix and prefix now accept and default tosuffix和prefix现在接受并默认为None
to cause an appropriate default value to be used.None
,以使用适当的默认值。Changed in version 3.6:版本3.6中更改:The dir parameter now accepts a path-like object.dir参数现在接受类似路径的对象。
-
tempfile.
mkdtemp
(suffix=None, prefix=None, dir=None)¶ Creates a temporary directory in the most secure manner possible.以尽可能安全的方式创建临时目录。There are no race conditions in the directory’s creation.目录的创建中没有竞争条件。The directory is readable, writable, and searchable only by the creating user ID.目录只能通过创建用户ID来读取、写入和搜索。The user ofmkdtemp()
is responsible for deleting the temporary directory and its contents when done with it.mkdtemp()
的用户负责删除临时目录及其内容。The prefix, suffix, and dir arguments are the same as forprefix、suffix和dir参数与mkstemp()
.mkstemp()
的参数相同。mkdtemp()
returns the absolute pathname of the new directory.返回新目录的绝对路径名。Raises an auditing event使用参数tempfile.mkdtemp
with argumentfullpath
.fullpath
引发审核事件tempfile.mkdtemp
。Changed in version 3.5:版本3.5中更改:suffix, prefix, and dir may now be supplied in bytes in order to obtain a bytes return value.suffix、prefix和dir现在可以以字节为单位提供,以获得字节返回值。Prior to this, only str was allowed.在此之前,只允许str。suffix and prefix now accept and default tosuffix和prefix现在接受并默认为None
to cause an appropriate default value to be used.None
,以使用适当的默认值。Changed in version 3.6:版本3.6中更改:The dir parameter now accepts a path-like object.dir参数现在接受类似路径的对象。
-
tempfile.
gettempdir
()¶ Return the name of the directory used for temporary files.返回用于临时文件的目录的名称。This defines the default value for the dir argument to all functions in this module.这为该模块中的所有函数定义了dir参数的默认值。Python searches a standard list of directories to find one which the calling user can create files in.Python搜索标准目录列表,以找到调用用户可以在其中创建文件的目录。The list is:列表为:The directory named by the由TMPDIR
environment variable.TMPDIR
环境变量命名的目录。The directory named by the由TEMP
environment variable.TEMP
环境变量命名的目录。The directory named by the由TMP
environment variable.TMP
环境变量命名的目录。A platform-specific location:平台特定位置:On Windows, the directories
C:\TEMP
,C:\TMP
,\TEMP
, and\TMP
, in that order.On all other platforms, the directories
/tmp
,/var/tmp
, and/usr/tmp
, in that order.
As a last resort, the current working directory.作为最后手段,当前工作目录。
The result of this search is cached, see the description of此搜索的结果将被缓存,请参阅下面的tempdir
below.tempdir
描述。
-
tempfile.
gettempdirb
()¶ Same as与gettempdir()
but the return value is in bytes.gettempdir()
相同,但返回值以字节为单位。New in version 3.5.版本3.5中新增。
-
tempfile.
gettempprefix
()¶ Return the filename prefix used to create temporary files.返回用于创建临时文件的文件名前缀。This does not contain the directory component.它不包含目录组件。
-
tempfile.
gettempprefixb
()¶ Same as与gettempprefix()
but the return value is in bytes.gettempprefix()
相同,但返回值以字节为单位。New in version 3.5.版本3.5中新增。
The module uses a global variable to store the name of the directory used for temporary files returned by 该模块使用一个全局变量来存储gettempdir()
. gettempdir()
返回的临时文件所使用的目录名。It can be set directly to override the selection process, but this is discouraged. 可以直接将其设置为覆盖选择过程,但不建议这样做。All functions in this module take a dir argument which can be used to specify the directory. 该模块中的所有函数都采用dir参数,该参数可用于指定目录。This is the recommended approach that does not surprise other unsuspecting code by changing global API behavior.这是推荐的方法,它不会通过更改全局API行为而让其他不知情的代码感到惊讶。
-
tempfile.
tempdir
¶ When set to a value other than当设置为非None
, this variable defines the default value for the dir argument to the functions defined in this module, including its type, bytes or str.None
的值时,此变量定义此模块中定义的函数的dir参数的默认值,包括其类型、字节或str。It cannot be a path-like object.它不能是类似路径的对象。If如果在除tempdir
isNone
(the default) at any call to any of the above functions exceptgettempprefix()
it is initialized following the algorithm described ingettempdir()
.gettempprefix()
之外的任何上述函数的任何调用中tempdir
为None
(默认值),则按照gettempprefix()
中描述的算法初始化。Note
Beware that if you set请注意,如果将tempdir
to a bytes value, there is a nasty side effect: The global default return type ofmkstemp()
andmkdtemp()
changes to bytes when no explicitprefix
,suffix
, ordir
arguments of type str are supplied.tempdir
设置为bytes值,则会产生一个恶劣的副作用:当没有提供str类型的显式prefix
、suffix
或dir
参数时,mkstemp()
和mkdtemp()
的全局默认返回类型将更改为bytes。Please do not write code expecting or depending on this.请不要编写期望或依赖于此的代码。This awkward behavior is maintained for compatibility with the historical implementation.保持这种笨拙的行为是为了与历史实现兼容。
Examples示例¶
Here are some examples of typical usage of the 以下是tempfile
module:tempfile
模块的一些典型用法示例:
>>> import tempfile
# create a temporary file and write some data to it
>>> fp = tempfile.TemporaryFile()
>>> fp.write(b'Hello world!')
# read data from file
>>> fp.seek(0)
>>> fp.read()
b'Hello world!'
# close the file, it will be removed
>>> fp.close()
# create a temporary file using a context manager
>>> with tempfile.TemporaryFile() as fp:
... fp.write(b'Hello world!')
... fp.seek(0)
... fp.read()
b'Hello world!'
>>>
# file is now closed and removed
# create a temporary directory using the context manager
>>> with tempfile.TemporaryDirectory() as tmpdirname:
... print('created temporary directory', tmpdirname)
>>>
# directory and contents have been removed
Deprecated functions and variables不推荐使用的函数和变量¶
A historical way to create temporary files was to first generate a file name with the 创建临时文件的历史方法是首先使用mktemp()
function and then create a file using this name. mktemp()
函数生成文件名,然后使用此名称创建文件。Unfortunately this is not secure, because a different process may create a file with this name in the time between the call to 不幸的是,这并不安全,因为在调用mktemp()
and the subsequent attempt to create the file by the first process. mktemp()
和随后第一个进程尝试创建文件之间,另一个进程可能会创建具有此名称的文件。The solution is to combine the two steps and create the file immediately. 解决方案是将这两个步骤结合起来,立即创建文件。This approach is used by mkstemp()
and the other functions described above.mkstemp()
和上述其他函数使用这种方法。
-
tempfile.
mktemp
(suffix='', prefix='tmp', dir=None)¶ -
Return an absolute pathname of a file that did not exist at the time the call is made.返回调用时不存在的文件的绝对路径名。The prefix, suffix, and dir arguments are similar to those ofprefix、suffix和dir参数与mkstemp()
, except that bytes file names,suffix=None
andprefix=None
are not supported.mkstemp()
的参数类似,只是不支持字节文件名、suffix=None
和prefix=None
。Warning
Use of this function may introduce a security hole in your program.使用此函数可能会在程序中引入安全漏洞。By the time you get around to doing anything with the file name it returns, someone else may have beaten you to the punch.当你用它返回的文件名做任何事情时,其他人可能已经把你打到了极点。mktemp()
usage can be replaced easily withNamedTemporaryFile()
, passing it thedelete=False
parameter:mktemp()
的用法可以很容易地替换为NamedTemporaryFile()
,并向其传递delete=False
参数:>>> f = NamedTemporaryFile(delete=False)
>>> f.name
'/tmp/tmptjujjt'
>>> f.write(b"Hello World!\n")
13
>>> f.close()
>>> os.unlink(f.name)
>>> os.path.exists(f.name)
False