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模块的更多相关文章

  1. python 创建临时文件和文件夹

    ----需要在程序执行时创建一个临时文件或目录,并希望使用完之后可以自动销毁掉. tempfile 模块中有很多的函数可以完成这任务.为了创建一个匿名的临时文件,可以使用tempfile.Tempor ...

  2. createNewFile创建空文件夹与createTempFile创建临时文件夹

    创建要注意的地方如下: <pre name="code" class="java"> File类的createNewFile根据抽象路径创建一个新的 ...

  3. pig脚本不需要后缀名(python tempfile模块生成pig脚本临时文件,执行)

    pig 脚本运行不需要后缀名 pig脚本名为tempfile,无后缀名 用pig -f tempfile 可直接运行 另外,pig tempfile也可以直接运行 这样就可以用python临时文件存储 ...

  4. 【Python】 tempfile模块 临时文件和目录的处理

    [tempfile] 惊奇地又发现了一个比较有意思的小模块. 在一些场景中我们经常需要自动生成一些临时文件,当然用简单的open函数,来创建一个隐藏文件可以实现.不过tempfile这个模块把一些有的 ...

  5. 美女面试官问我Python如何优雅的创建临时文件,我的回答....

    [摘要] 本故事纯属虚构,如有巧合,他们故事里的美女面试官也肯定没有我的美,请自行脑补... 小P像多数Python自学者一样,苦心钻研小半年,一朝出师投简历. 这不,一家招聘初级Python开发工程 ...

  6. python标准库介绍——17 tempfile 模块详解

    ==tempfile 模块== [Example 2-6 #eg-2-6] 中展示的 ``tempfile`` 模块允许你快速地创建名称唯一的临时文件供使用. ====Example 2-6. 使用 ...

  7. TempFile模块

    tempfile模块,用来对临时数据进行操作 tempfile 临时文件(夹)操作 tempfile.mkstemp([suffix="[, prefix='tmp'[, dir=None[ ...

  8. python基础31[常用模块介绍]

    python基础31[常用模块介绍]   python除了关键字(keywords)和内置的类型和函数(builtins),更多的功能是通过libraries(即modules)来提供的. 常用的li ...

  9. Python标准库tempfile的使用总结

    Python标准库tempfile的使用总结 临时文件是计算机程序存储临时数据的文件,它的扩展名通常是".temp".本文用于记录使用Python提供的临时文件API解决实际问题的 ...

随机推荐

  1. Ios学习之容器的理解

    UInavgationController 和 UITabbarController 都是容器 1:uinavigationcontroller (导航控制器) uinavigationcontrol ...

  2. C#开发微信公众平台(附Demo)

    服务号和订阅号 服务号是公司申请的微信公共账号,订阅号是个人申请的,我个人也申请了一个,不过没怎么用. 服务号 1个月(30天)内仅可以发送1条群发消息. 发给订阅用户(粉丝)的消息,会显示在对方的聊 ...

  3. MyEclipse 8.5汉化教程

    汉化包下载:http://yunpan.cn/QIUaVS2CU5wCd 1.解压MyEclipse中的language文件夹 以我的安装目录为例,我的MyEclipse8.5的安装在D:盘下.将解压 ...

  4. iPhone手机安全指南

    摘要:iPhone手机安全指南 - 1.iPhone解锁使用指纹:2.启用“查找我的iPhone”功能:3.Apple ID启用两步验证:4.修改SIM卡PIN码.5.iPhone被盗或丢失后,登录i ...

  5. 笔记26-徐 SQLSERVER内存分配和常见内存问题

    1 --64位SQLSERVER   应用在IA64操作系统                         7TB                         2TB               ...

  6. 搭建MySQL MHA高可用

    本文内容参考:http://www.ttlsa.com/mysql/step-one-by-one-deploy-mysql-mha-cluster/ MySQL MHA 高可用集群 环境: Linu ...

  7. 336-Palindrome Pairs

    336-Palindrome Pairs Given a list of unique words, find all pairs of distinct indices (i, j) in the ...

  8. Magento1.9批量修改产品 Attribute Set

    今天修改产品时遇到这样一个需求:重新设置产品的 Attribute Set,使用的是Magento1.9系统,Magento提供这样一个插件 Flagbit Change Attribute Set: ...

  9. nw_socket_handle_socket_event解决

    http://www.bkjia.com/IOSjc/1158465.html 出现问题如下 to a parent directory scheduled for deletion nw_endpo ...

  10. SQL 分页

    sql = "SELECT TOP 10000 * " + " FROM(SELECT ROW_NUMBER() OVER(ORDER BY DataArticleID) ...