python tempfile 模块---生成临时文件和目录


该模块用于创建临时文件和目录,它可以跨平台使用。TemporaryFile、NamedTemporaryFile、TemporaryDirectory 和 SpooledTemporaryFile 是带有自动清理功能的高级接口,可用作上下文管理器。mkstemp() 和 mkdtemp() 是低级函数,使用完毕需手动清理。

1 tempfile介绍

tempfile 模块中常用的函数,如下表所示。

tempfile 模块函数 功能描述
tempfile.TemporaryFile(mode=‘w+b’, buffering=None, encoding=None, newline=None, suffix=None, prefix=None, dir=None) 创建临时文件。该函数返回一个类文件对象,也就是支持文件 I/O。
tempfile.NamedTemporaryFile(mode=‘w+b’, buffering=None, encoding=None, newline=None, suffix=None, prefix=None, dir=None, delete=True) 创建临时文件。该函数的功能与上一个函数的功能大致相同,只是它生成的临时文件在文件系统中有文件名。
tempfile.SpooledTemporaryFile(max_size=0, mode=‘w+b’, buffering=None, encoding=None, newline=None, suffix=None, prefix=None, dir=None) 创建临时文件。与 TemporaryFile 函数相比,当程序向该临时文件输出数据时,会先输出到内存中,直到超过 max_size 才会真正输出到物理磁盘中。
tempfile.TemporaryDirectory(suffix=None, prefix=None, dir=None) 生成临时目录。
tempfile.gettempdir() 获取系统的临时目录。
tempfile.gettempdirb() 与 gettempdir() 相同,只是该函数返回字节串。
tempfile.gettempprefix() 返回用于生成临时文件的前缀名。
tempfile.gettempprefixb() 与 gettempprefix() 相同,只是该函数返回字节串。

提示:表中有些函数包含很多参数,但这些参数都具有自己的默认值,因此如果没有特殊要求,可以不对其传参。

2 创建临时文件

2.1 TemporaryFile

该函数返回一个类文件对象,用于临时数据保存(实际上对应磁盘上的一个临时文件)。

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

生成的对象可以用作上下文管理器。完成文件对象的上下文或销毁后(文件对象被 close 或者被 del),临时文件将从文件系统中删除。

  • mode 参数默认值为 w+b,采用二进制模式,可以进行读写
  • buffering 用于设置缓冲策略。0:关闭缓冲(仅允许在二进制模式下),1:行缓冲(仅在文本模式下可用),>1 的整数:指定块缓冲区的大小(以字节为单位)。如果没有给出 buffering 参数,采用默认缓冲策略
  • encoding 是用于解码或编码文件的编码的名称
  • prefix 指定了临时文件名的前缀
  • suffix 指定了临时文件名的后缀
  • dir 用于设置临时文件默认的保存路径
  • 返回的类文件对象有一个 file 属性,它指向真正操作的底层的 file 对象
from tempfile import TemporaryFile

temp = TemporaryFile(dir='/home/skx/pra')
print(temp)
print(temp.name)

'''
TemporaryFile类的构造方法,其返回的还是一个文件对象。但这个文件对象特殊的地方在于
1. 对应的文件没有文件名,对除了本程序之外的程序不可见
2. 在被关闭的同时被删除
所以上面的两句打印语句,输出分别是一个文件对象,以及一个<fdopen>(并不是文件名)
'''
# 向临时文件中写入内容
temp.write(b'hello\nworld')
temp.seek(0)  # 将文件指针移动到头部,准备读取文件
print(temp.read())
temp.close()  # 关闭文件的同时删除文件

# 通过with语句创建临时文件,with会自动关闭临时文件
with TemporaryFile() as fd:
    fd.write("我最棒".encode('utf-8'))
    fd.seek(0)
    print(fd.read().decode('utf-8'))
<_io.BufferedRandom name=3>
3
b'hello\nworld'
我最棒

注意:mode 参数默认值为 w+b,写 str 时每次需要转换为 binary 再写入,这样很麻烦,可以指定打开方式为 w+,这样就可以直接进行 str 类型的读写了

读取配置文件放入临时文件

  • example.ini
[DEFAULT]
ip = 172.0.0.1
port = 22

[bitbucket.org]
user = Atlan
  • conf_tempfile.py
#coding=utf-8
import configparser
from tempfile import TemporaryFile

conf = configparser.ConfigParser()
conf.read('example.ini')
with TemporaryFile(mode='w+') as fd:
    conf.write(fd)          # 注意这里的用法
    fd.seek(0)
    print(fd.read())

2.2 NamedTemporaryFile

此函数执行的操作与 TemporaryFile() 完全相同,但是创建的临时文件有文件名,在文件系统中可以找到,因此可以多个进程同时访问

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

该函数多了一个 delete 参数,用于指定类文件对象 close 或者被 del 之后,是否也一同删除磁盘上的临时文件(当 delete = True 的时候,行为与 TemporaryFile 一样)。

import os
from tempfile import NamedTemporaryFile

# 指定文件以 "head_" 开头,以"_tail"结尾
temp = NamedTemporaryFile(suffix="_tail", prefix="head_", dir='/home/skx/pra',delete=False)
try:
    print('temp:', temp)
    print('temp.name:', temp.name)
finally:
    temp.close()
# 指定了delete,文件对象 close 或者被 del 之后,磁盘文件不会被删除
print('Exists after close:', os.path.exists(temp.name))

运行结果:

temp: <tempfile._TemporaryFileWrapper object at 0x7f17ac9bf0b8>
temp.name: /home/skx/pra/head_0dsw2361_tail
Exists after close: True

指定 delete=False,文件对象 close 或者被 del 之后,不删除磁盘上的临时文件,在指定的目录中可以看到文件如下
在这里插入图片描述

2.3 SpooledTemporaryFile

tempfile.SpooledTemporaryFile(max_size=0, mode='w+b', buffering=-1, 
                              encoding=None, newline=None, 
                              suffix=None, prefix=None, dir=None, *, errors=None)

此函数执行的操作与 TemporaryFile() 完全相同,但会将数据缓存在内存中,直到文件大小超过 max_size,或调用文件的 fileno() 方法为止,此时数据会被写入磁盘。

2.4 mkstemp

tempfile.mkstemp(suffix=None, prefix=None, dir=None, text=False)
  • prefix 指定了临时文件名的前缀
  • suffix 指定了临时文件名的后缀
  • dir 用于设置临时文件默认的保存路径
  • text 指定了是否以文本的形式来操作文件,默认为False,表示以二进制的形式来操作文件。

mkstemp() 返回一个元组,元组中第一个元素是句柄,它是一个系统级句柄,指向一个打开的文件(等同于 os.open() 的返回值),第二元素是该文件的绝对路径。

文件使用完后文件不会自动清除,需要手动清理。

import tempfile
tmp_f = tempfile.mkstemp(dir="/home/skx/pra/")
print(tmp_f)	# (3, '/home/skx/pra/tmp58do2j53')--> tmp_f[0] 是句柄,tmp_f[1] 是文件路径

fd = tmp_f[1]

with open(fd, 'w+') as f:
    f.write('Hello world')
    f.seek(0)
    print(f.read())

运行结果

(3, '/home/skx/pra/tmp58do2j53')
Hello world

3 创建临时目录

3.1 TemporaryDirectory

tempfile.TemporaryDirectory(suffix=None, prefix=None, dir=None)
  • prefix 指定了临时文件名的前缀
  • suffix 指定了临时文件名的后缀
  • dir 用于设置临时文件默认的保存路径

此函数会安全地创建一个临时目录。此函数返回的对象可用作上下文管理器。完成上下文或销毁临时目录对象后,新创建的临时目录及其所有内容自动将从文件系统中删除。

也可以调用 cleanup() 方法手动清理目录。

import os
import tempfile

with tempfile.TemporaryDirectory(suffix='_tail', prefix='head_') as dir_name:
    print(dir_name)

print(os.path.exists(dir_name))

运行结果

/tmp/head_gtbt2gkw_tail
False

3.2 mkdtemp

def mkdtemp(suffix=None, prefix=None, dir=None)
  • prefix 指定了临时文件名的前缀
  • suffix 指定了临时文件名的后缀
  • dir 用于设置临时文件默认的保存路径

以最安全的方式创建一个临时目录,创建该目录时不会有竞争的情况。该目录只能由创建者读取、写入和搜索。返回新目录的绝对路径名。

用户用完临时目录后需要自行将其删除

import os
import tempfile

dir_name = tempfile.mkdtemp(suffix='_tail', prefix='head_', dir='/tmp')
print(dir_name)
# 需要手动清理
os.removedirs(dir_name)

运行结果

/tmp/head_kn9uoe1z_tail

猜你喜欢

转载自blog.csdn.net/happyjacob/article/details/112385665