[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

时间: 2024-10-04 02:45:43

[python] 创建临时文件-tempfile模块的相关文章

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

pig 脚本运行不需要后缀名 pig脚本名为tempfile,无后缀名 用pig -f tempfile 可直接运行 另外,pig tempfile也可以直接运行 这样就可以用python临时文件存储pig脚本内容直接调用 python调用pig脚本的一种方式 将pig脚本用任意文件存储,执行时写入python的临时文件(tempfile模块操作),执行结束后删除.执行过程: 用tempfile模块NamedTemporaryFile生成临时文件,名字默认随机,然后,可以用tempfile.na

Python创建模块(第五章:模块)

模块提供了一种程序之间共享python代码的便捷方式.python提供了几百个模块的库,您可以在脚步中调用它们,也可以创建自己的模块. 本章介绍 研究模块的内部机制 创建一个仅包含函数的模块 在模块中定义类 通过子类扩展类 定义异常来报告错误状态 为模块建立文档 测试模块 将模块作为程序运行 安装模块 5.1研究模块 模块只是一个python源文件,它可以包含变量,类,函数和python脚本中可用到的其他任何元素. 通过使用dir函数可以更好地理解模块,给dir函数传递某个python元素(例如

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

python基础31[常用模块介绍] python除了关键字(keywords)和内置的类型和函数(builtins),更多的功能是通过libraries(即modules)来提供的. 常用的libraries(modules)如下: 1)python运行时服务 * copy: copy模块提供了对复合(compound)对象(list,tuple,dict,custom class)进行浅拷贝和深拷贝的功能. * pickle: pickle模块被用来序列化python的对象到bytes流,从

tempfile 模块

tempfile 模块允许你快速地创建名称唯一的临时文件供使用. 其他的应用程序无法找到或打开这个临时文件,它并没有引用文件系统表.用这个函数创建的临时文件,关闭后会自动删除. 1 __author__ = 'Zechary' 2 3 import os 4 import tempfile 5 6 temp = tempfile.TemporaryFile() 7 try: 8 temp.write('abcdefg') 9 temp.seek(0) 10 print temp.read() 1

Python基础5-常用模块

本节大纲 模块介绍 time &datetime模块 random os sys shutil shelve xml处理 yaml处理 configparser hashlib subprocess logging模块 re正则表达式 模块,就是实现某种或者某类功能代码的合集. 类似于函数式编程和面向过程编程,函数式编程完成一个功能,其他代码可以调用,提供了代码的重用性跟代码间的耦合.对于一个复杂的功能,可能需要多个函数才能完成,多个.py文件的代码集合就叫做模块. 如:os是系统相关的模块:f

python下通过os模块和shutil模块进行文件处理方式

python下通过os模块和shutil模块进行文件处理方式 得到当前工作目录路径:os.getcwd() 获取指定目录下的所有文件和目录名:os.listdir(dir) 删除文件:os.remove(file) 删除多个目录:os.removedirs(r"/home") 检测路径是否为文件:os.path.isfile(path) 检测路径是否为目录:os.path.isdir(path) 判断是否为绝对路径:os.path.isabs(path) 检测路径是否存在:os.pat

2015/9/15 Python基础(12):模块和包

模块是用来组织 Python 代码的方法,而包则是用来组织模块的. 当代码量很大时,我们一般会把代码分成几个有组织的代码段,然后每个代码段之间有一定的联系.代码单之间是共享的,所以Python允许调入一个模块,允许使用其他模块的属性利用之前的工作成果,实现代码重用.那些自我包含并且有组织的代码片段就是模块(module),将其他模块中属性附加到你的模块中的操作较导入(import) 模块是逻辑上的说法,而它们在物理层是一个个独立的文件,模块的文件名就是模块的名字加拓展名.py.与其他可以导入类的

Python学习笔记-邮件模块SMTP

smtplib模块: SMTP(Simple Mail Transfer Protocol)即简单邮件传输协议,它是一组用于由源地址到目的地址传送邮件的规则,由它来控制信件的中转方式. python的smtplib提供了一种很方便的途径发送电子邮件.它对smtp协议进行了简单的封装. Python创建 SMTP 对象语法如下: import smtplib smtpObj = smtplib.SMTP( [host [, port [, local_hostname]]] ) 参数说明: hos

python 的日志logging模块学习

最近修改了项目里的logging相关功能,用到了python标准库里的logging模块,在此做一些记录.主要是从官方文档和stackoverflow上查询到的一些内容. 官方文档 技术博客 基本用法 下面的代码展示了logging最基本的用法. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 # -*- cod