[python] 创建临时文件-tempfile模块

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[python] 创建临时文件-tempfile模块相关的知识,希望对你有一定的参考价值。

This module generates temporary files and directories. It works on all supported platforms.
In version 2.3 of Python, this module was overhauled重写 for enhanced security. It now provides three new functions,
NamedTemporaryFile(), mkstemp(), and mkdtemp(), which should eliminate all remaining need to use
the insecure mktemp() function. Temporary file names created by this module no longer contain the process ID;
instead a string of six random characters is used.
Also, all the user-callable functions now take additional arguments which allow direct control over the location and
name of temporary files. It is no longer necessary to use the global tempdir and template variables. 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 functions

  ***tempfile.TemporaryFile([mode=’w+b’[, bufsize=-1[, suffix=’‘[, prefix=’tmp’[, dir=None]]]]]

Return a file-like object that can be used as a temporary storage area. The file is created using 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 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 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.
bufsize defaults to -1, meaning that the operating system default is used.
The dir, prefix and suffix parameters are passed to mkstemp().
The returned object is a true file object on POSIX platforms. On other platforms, it is a file-like object whose
file attribute is the underlying true file object. This file-like object can be used in a with statement, just
like a normal file.

该函数返回一个 类文件对象(file-like)用于临时数据保存(实际上对应磁盘上的一个临时文件)。当文件对象被close或者被del的时候,临时文件将从磁盘上删除。mode、bufsize参数的单方与open()函数一样;suffix和prefix指定了临时文件名的后缀和前缀;dir用于设置临时文件默认的保存路径。返回的类文件对象有一个file属性,它指向真正操作的底层的file对象。

dir参数指定临时文件保存于的目录

 

  ****tempfile.NamedTemporaryFile([mode=’w+b’[, bufsize=-1[, suffix=’‘[, prefix=’tmp’[,dir=None[delete=True]]]]]]
 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). That name can be retrieved恢复
from the name attribute of the returned file-like object. 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). If delete is true (the default), the file is deleted as soon as it is closed.
The returned object is always a file-like object whose file attribute is the underlying true file object. This
file-like object can be used in a with statement, just like a normal file.

 tempfile.NamedTemporaryFile函数的行为与tempfile.TemporaryFile类似,只不过它多了一个delete参数,用于指定类文件对象close或者被del之后,是否也一同删除磁盘上的临时文件(当delete = True的时候,行为与TemporaryFile一样);如果临时文件会被多个进程或主机使用,那么建立一个有名字的文件是最简单的方法。这就是NamedTemporaryFile要做的,可以使用name属性访问它的名字;dir参数指明临时文件要保存于的目录。

  ***tempfile.SpooledTemporaryFile([max_size=0[, mode=’w+b’[, bufsize=-1[, suffix=’‘[, prefix=’tmp’[, dir=None]]]]]])

This function operates exactly as TemporaryFile() does, except that data is spooled in memory until
the file size exceeds max_size, or until the file’s fileno() method is called, at which point the contents
are written to disk and operation proceeds as with TemporaryFile(). Also, it’s truncate method
does not accept a size argument.
The resulting file has one additional method, rollover(), which causes the file to roll over to an on-disk
file regardless of its size.
The returned object is a file-like object whose _file attribute is either a StringIO object or a true file
object, depending on whether rollover() has been called. This file-like object can be used in a with
statement, just like a normal file.

tempfile.SpooledTemporaryFile函数的行为与tempfile.TemporaryFile类似。不同的是向类文件对象写数据的时候,数据长度只有到达参数max_size指定大小时,或者调用类文件对象的fileno()方法,数据才会真正写入到磁盘的临时文件中。

  ***tempfile.mkstemp([suffix=’‘[, prefix=’tmp’[, 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 for os.open(). The file
is readable and writable only by the creating user 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 of mkstemp() is responsible for deleting the temporary file when
done with it.

mkstemp方法用于创建一个临时文件。该方法仅仅用于创建临时文件,调用tempfile.mkstemp函数后,返回包含两个元素的元组,第一个元素指示操作该临时文件的安全级别,第二个元素指示该临时文件的路径。参数suffix和prefix分别表示临时文件名称的后缀和前缀;dir指定了临时文件所在的目录,如果没有指定目录,将根据系统环境变量TMPDIRTEMP或者TMP的设置来保存临时文件;参数text指定了是否以文本的形式来操作文件,默认为False,表示以二进制的形式来操作文件。


If suffix is specified, the file name will end with that suffix, otherwise there will be no suffix. mkstemp()
does not put a dot between the file name and the suffix; if you need one, put it at the beginning of suffix.
If prefix is specified, the file name will begin with that prefix; otherwise, a default prefix is used.
If dir is specified, the file will be created in that directory; otherwise, a default directory is used. 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. 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().
If text is specified, it indicates whether to open the file in binary mode (the default) or text mode. On some
platforms, this makes no difference.
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

  ***tempfile.mkdtemp([suffix=’‘[, prefix=’tmp’[, 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.
The user of mkdtemp() is responsible for deleting the temporary directory and its contents内容 when done
with it.
The prefix, suffix, and dir arguments are the same as for mkstemp().
mkdtemp() returns the absolute pathname of the new directory.

该函数用于创建一个临时文件夹,它返回临时文件夹的绝对路径。
  ***tempfile.tempdir
When set to a value other than None, this variable defines the default value for the dir argument to all the
functions defined in this module.
If tempdir is unset or None at any call to any of the above functions, Python searches a standard list of
directories and sets tempdir to the first one which the calling user can create files in. The list is:
1.The directory named by the TMPDIR environment variable.
2.The directory named by the TEMP environment variable.
3.The directory named by the TMP environment variable.
4.A platform-specific location:
?On RiscOS, the directory named by the Wimp$ScrapDir environment variable.
?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.
5.As a last resort, the current working directory.
该属性用于指定创建的临时文件(夹)所在的默认文件夹。如果没有设置该属性或者将其设为None,Python将返回以下环境变量TMPDIR, TEMP, TEMP指定的目录,如果没有定义这些环境变量,临时文件将被创建在当前工作目录。

  ***tempfile.gettempdir()
Return the directory currently selected to create temporary files in. If tempdir is not None, this simply
returns its contents; otherwise, the search described above is performed, and the result returned.

gettempdir()则用于返回保存临时文件的文件夹路径。

  ***tempfile.gettempprefix()
Return the filename prefix used to create temporary files. This does not contain the directory component.
Using this function is preferred over reading the template variable directly





















































































以上是关于[python] 创建临时文件-tempfile模块的主要内容,如果未能解决你的问题,请参考以下文章

Python tempfile (临时文件)

tempfile库:Python临时文件系统对象

tempfile库:Python临时文件系统对象

Python ——tempfile

Python标准库tempfile的使用总结

当我在多线程中使用 #Fabric put# 将 tempfile.mkstemp 创建的临时文件复制到远程文件时找不到文件