python中tempfile库用法详解
  TEZNKK3IfmPf 2023年11月13日 12 0

1、应用场景介绍:

        tempfile模块是用来创建临时文件或者文件夹的跨平台工具。在大型数据处理项目中,有的处理结果是不需要向用户最终展示的,但是它们的应用又是贯穿项目始终的,在这种情况下,就需要使用tempfile模块来解决这种问题。

2、tempfile安装

        tempfile为内置库,不需要安装。

 源码解读:

"""Temporary files.

This module provides generic, low- and high-level interfaces for
creating temporary files and directories.  All of the interfaces
provided by this module can be used without fear of race conditions
except for 'mktemp'.  'mktemp' is subject to race conditions and
should not be used; it is provided for backward compatibility only.

The default path names are returned as str.  If you supply bytes as
input, all return values will be in bytes.  Ex:

    >>> tempfile.mkstemp()
    (4, '/tmp/tmptpu9nin8')
    >>> tempfile.mkdtemp(suffix=b'')
    b'/tmp/tmppbi8f0hy'

This module also provides some data items to the user:

  TMP_MAX  - maximum number of names that will be tried before
             giving up.
  tempdir  - If this is set to a string before the first use of
             any routine from this module, it will be considered as
             another candidate location to store temporary files.
"""

3、模块方法介绍

tempfile模块主要包括三类函数:

        四个高级接口:TemporaryFile、NamedTemporaryFile、SpooledTemporaryFile和TemporaryDirectory,这四个高级接口提供了自动清除功能并且可以作为上下文管理器使用。

函数名 描述
TemporaryFileNamedTemporaryFile 高级临时文件对象创建函数
SpooledTemporaryFile 假脱机模式高级临时文件对象创建函数
TemporaryDirectory 高级临时目录创建函数

        两个底层函数mkstemp()和mkdtemp(),用于生成临时底层的临时文件和文件夹,在使用完它们的时候需要手动清除。

函数名 描述
mkstemp() 底层临时文件创建函数
mkdtemp() 底层临时目录创建函数

        tempfile模块还有一些针对文件、文件夹属性的操作函数gettempdir()、gettempdirb()、gettempprefix、gettempprefixb。

函数名 描述
gettempdir() 以文本格式返回临时文件夹名函数
gettempdirb() 以二进制格式返回临时文件夹名函数
gettempprefix 以文本格式返回临时文件名前缀
gettempprefixb 以二进制格式返回临时文件名前缀

        tempfile的所有用户可调用函数和构造函数都带有额外参数,通过这些参数可以实现对临时文件目录和位置的管理。此模块会在共享临时目录中安全地创建临时文件,并给创建临时文随机起个名。

3.1 Temporaryfile函数

        Temporaryfile函数返回一个类文件对象用作临时存储区,它使用与mkstemp()函数相同规则的安全重建文件模式,它一关闭就会被销毁(包括针对垃圾收集对象的隐式关闭)。需要注意的是,在Unix系统环境,文件的目录要么根本不创建,要么在文件创建后立即删除。也就是说,代码不会依赖于此函数创建的临时文件,包括它们的名称,这也是这个函数与NamedTemporaryfile函数的不同之处。

语法结构:

TemporaryFile(mode='w+b', buffering=-1, encoding=None,
                      newline=None, suffix=None, prefix=None,
                      dir=None)

参数介绍:

  • mode参数:默认为w+r,以便文件在被创建时可以执行读写操作。
  • buffering、encoding、errors和newline参数:用于解释open()函数行为。
  • dir、prefix和suffix参数:与mkstemp()具有相同的含义和默认设置。

示例代码:

import tempfile

# 创建临时文件并写入数据
fp = tempfile.TemporaryFile()
fp.write(b'TemporaryFile Test!')

# 读取数据
fp.seek(0)
res = fp.read()
print(res)

运行结果:

python中tempfile库用法详解

使用上下文管理或销毁文件对象后,临时文件将从文件系统中删除。

示例代码1:  【错误写法】

import tempfile

# 创建临时文件并写入数据
with tempfile.TemporaryFile() as fp:
    fp.write(b'TemporaryFile Test!')

# 读取数据
# fp.seek(0)  # ValueError: seek of closed file
res = fp.read()  # ValueError: read of closed file
print(res)

运行结果:

python中tempfile库用法详解

示例代码2:

import tempfile

# 创建临时文件并写入数据
with tempfile.TemporaryFile() as fp:
    fp.write(b'TemporaryFile Test!')

    # 读取数据
    fp.seek(0)
    res = fp.read()
    print(res)

运行结果:

python中tempfile库用法详解

3.2 NamedTemporaryfile函数

        除了NamedTemporaryfile()函数实现了在文件系统中只有一个可见名之外,其作用与TemporaryFile()功能完全相同。执行完该函数后,我们可以从返回的类文件对象的name属性中检索文件名称。在Unix系统上,在命名的临时文件处于打开状态时,可以使用该名称打开生成的文件。

语法结构:

NamedTemporaryFile(mode='w+b', buffering=-1, encoding=None,
                       newline=None, suffix=None, prefix=None,
                       dir=None, delete=True)

参数说明:

  • delete参数选项:如果该参数为True(默认),则文件一关闭则被删除。返回的对象始终是一个类文件对象,其文件属性是底层的真实文件对象。也就是说,这个类文件对象可以在with上下文管理中使用,就像普通文件一样。

3.3 SpooledTemporaryfile函数

        。。。

3.4 TemporaryDirectory函数

        。。。

3.5 mkstemp函数

        。。。

3.6 mkdtemp函数

        。。。

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月13日 0

暂无评论

推荐阅读
  TEZNKK3IfmPf   2024年05月31日   32   0   0 python开发语言
  TEZNKK3IfmPf   2024年05月31日   25   0   0 python
  TEZNKK3IfmPf   2024年05月31日   34   0   0 excelpython
  TEZNKK3IfmPf   2024年05月31日   25   0   0 python
TEZNKK3IfmPf