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. html5 定位 获得当前位置的经纬度

    if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(showPosition, showError, { // ...

  2. 过渡transitioin

    一,什么是过渡(transition)? 1,transition 允许 CSS 元素的属性值在一定的时间区间内平滑地过渡. 2,可以在不使用 Flash 动画或 JavaScript 的情况下,在元 ...

  3. git入门札记

    分布式版本控制(个人主机即版本库,有一台作为“中央服务器”来方便“交换”修改,管理修改 而非文件) vs.  SVN CVS git 安装后设置: git config - -global user. ...

  4. iOS返回一个前面没有0,小数点后保留两位的数字字符串

    /* * 处理一个数字加小数点的字符串,前面无0,保留两位.网上有循环截取的方法,如果数字过长,浪费内存,这个方法在优化内存的基础上设计的. */ -(NSString*)getTheCorrectN ...

  5. rabbitMQ学习(四)

    按照routing key接收信息 发送端: public class EmitLogDirect { private static final String EXCHANGE_NAME = &quo ...

  6. NodeJs解析web一例

    var http = require('http'); var fs = require('fs'); var url = require('url'); http.createServer(func ...

  7. avalon2.2.3发布

    avalon2.2.3这次发布带许多好的东西 首先正式有了自己的LOGO 其次有了自己的QuickStart 样例工程, 这个工程整合了路由,表单,表格,切换卡等组件 https://github.c ...

  8. svn更新操作时提示database is locked

    If you're on Windows version just let's do the next: Right click on the repo folder and go to Tortoi ...

  9. Beat版本分工

    柯晓鸿031302613:负责服务器的搭建,struts2框架的配置,后台与页面的连整合,部分后台接口,数据库连接查询接口,以及页面js的书写 比例:40% 洪腾飞031302608:负责主要界面的书 ...

  10. Linux驱动学习之什么是驱动?

    一.什么是驱动? 1: 驱动一词的字面意思 2: 物理上的驱动 3: 硬件中的驱动 4: linux内核驱动.软件层面上的驱动广义上是指:这一段代码操作了硬件去动,所以这一段代码就叫硬件的驱动程序. ...