首页 > 其他分享 >tempfile库:创建临时文件系统

tempfile库:创建临时文件系统

时间:2022-09-28 18:23:51浏览次数:54  
标签:None tempfile 创建 fp1 临时文件 dir

tempfile库介绍

tempfile属于python的标准库,无需安装,直接导入即可使用。tempfile 模块专门用于创建临时文件和临时目录,它既可以在 UNIX 平台上运行良好,也可以在 Windows 平台上运行良好

在实际的项目处理中,往往我们并不需要创建文件,仅仅用于中转而已。这个时候在系统中频繁的创建中转文件,删除中转文件,不仅浪费系统的资源,而且容易被破坏或者篡改,这个时候用临时文件反而更好

 

tempfile常用方法或类

  1. TemporaryFile:创建临时文件,一旦文件关闭,就立即被销毁;
  2. NamedTemporaryFile:创建有名字的、在文件系统中可见的临时文件,可以通过指定delete参数设置文件关闭时是否删除临时文件,默认为True删除;
  3. SpooledTemporaryFile:创建临时文件。与 TemporaryFile 函数相比,当程序向该临时文件输出数据时,会先输出到内存中,直到超过 max_size 才会真正输出到物理磁盘中
  4. TemporaryDirectory:创建临时文件夹;
  5. mkstemp():创建临时文件,需要手动关闭和销毁;
  6. mkdtemp():创建临时文件夹,需要手动关闭和销毁。

TemporaryFile

创建临时文件,一旦文件关闭,就立即被销毁,以下是可传的参数,大部分参数默认即可

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

mode:表示临时文件的模式(w+b表示二进制的读写模式),默认即可

buffering:缓冲区设置,默认即可(

buffering= -1 t和b都是io.DEFAULT_BUFFER_SIZE
buffering=0 二进制模式 关闭缓冲区,文本模式不支持
buffering=1 文本模式行缓冲,遇到换行符才flush
buffering>1 二进制模式表示缓冲大小。缓冲区的值可以超过 io.DEFAULT_BUFFER_SIZE,直到设定的值超出后才把缓冲区flush,文本模式,是io.DEFAULT_BUFFER_SIZE字节,flush完后把当前字符串也写入磁盘

encoding:编码格式

newline:将输出写入流时,如果 newline 为 None,则写入的任何 ‘\n’ 字符都将转换为系统默认行分隔符 os.linesep。如果 newline 是 ‘’ 或 ‘\n’,则不进行翻译。如果 newline 是任何其他合法值,则写入的任何 ‘\n’ 字符将被转换为给定的字符串。

suffix:临时文件名后缀

prefix:临时文件名前缀

dir:指定临时文件所在的目录,如果没有指定目录,将根据系统环境变量TMPDIR,TEMP或者TMP的设置来保存临时文件

其余几个方法的参数也都是大致类似作用

tempfile.TemporaryFile()创建实例化对象后,返回的是临时文件的绝对路径

可以使用两种方法来操作临时文件的读写:

1、直接write写入,但需要手动close

2、使用with来创建临时文件,with会自动关闭

import tempfile
import shutil
import os
fp = tempfile.TemporaryFile()
print(fp.name)
fp.write('你好'.encode('utf-8'))
fp.write('世界'.encode('utf-8'))
#将文件指针移到开头,读取文件
fp.seek(0)
print(fp.read().decode('utf-8'))
#关闭文件,文件会被自动删除
fp.close()

with tempfile.TemporaryFile() as fp:
    print(fp.name)
    fp.write('床前明月光'.encode('utf-8'))
    fp.write('疑是地上霜'.encode('utf-8'))
    fp.seek(0)
    print(fp.read().decode('utf-8'))

 

打印如下:

C:\Users\haolin\AppData\Local\Temp\tmp2qznp6re
你好世界
C:\Users\haolin\AppData\Local\Temp\tmpbz72j4av
床前明月光疑是地上霜

 

 

NamedTemporaryFile

创建有名字的、在文件系统中可见的临时文件,相较于TemporaryFile,可以通过指定delete参数设置文件关闭时是否删除临时文件,默认为True删除

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

将delete设置为False:

with tempfile.NamedTemporaryFile(delete=False) as tp:
    tp.write('两只老虎爱跳舞'.encode('utf-8'))
    print(tp.name)

 

输出结果:

C:\Users\haolin\AppData\Local\Temp\tmpsb106d_n

文件管理系统打开此临时文件(记事本打开),可以看到临时文件未被删除,且文件里面存在刚才所输入的字符串

 

SpooledTemporaryFile

创建临时文件。与 TemporaryFile 函数相比,它直接是个类,而不是方法,且多了一个max_size参数,默认为0,当程序向该临时文件输出数据时,会先输出到内存中,直到超过 max_size 才会真正输出到物理磁盘中

源码:

class SpooledTemporaryFile:
    """Temporary file wrapper, specialized to switch from BytesIO
    or StringIO to a real file when it exceeds a certain size or
    when a fileno is needed.
    """
    _rolled = False

    def __init__(self, max_size=0, mode='w+b', buffering=-1,
                 encoding=None, newline=None,
                 suffix=None, prefix=None, dir=None):

 

 创建临时文件代码:

with tempfile.SpooledTemporaryFile() as tf:
    tf.write('img'.encode('utf-8'))
    tf.seek(0)
    print(tf.read().decode('utf-8'))
    print(tf.name)

 

 

输出:

img
None

 

可以看到max_size默认为0时,临时文件并没有创建,写入的数据是在内存当中,并没有写入到硬盘,当把max_size改为1时:

with tempfile.SpooledTemporaryFile(max_size=1) as tf:
    tf.write('img'.encode('utf-8'))
    tf.seek(0)
    print(tf.read().decode('utf-8'))
    print(tf.name)

 

输出:

img
C:\Users\haolin\AppData\Local\Temp\tmptwr2afru

 

"img"字符串大于所设定的1bytes,所以数据被写入到硬盘中

 

TemporaryDirectory

创建临时文件夹,创建方式与TemporaryFile一致,可以使用with来操作

源码:

class TemporaryDirectory(object):
    """Create and return a temporary directory.  This has the same
    behavior as mkdtemp but can be used as a context manager.  For
    example:

        with TemporaryDirectory() as tmpdir:
            ...

    Upon exiting the context, the directory and everything contained
    in it are removed.
    """

    def __init__(self, suffix=None, prefix=None, dir=None):
        self.name = mkdtemp(suffix, prefix, dir)
        self._finalizer = _weakref.finalize(
            self, self._cleanup, self.name,
            warn_message="Implicitly cleaning up {!r}".format(self))

 

代码:

with tempfile.TemporaryDirectory() as tempdirname:
    print(tempdirname)

 

输出:

C:\Users\haolin\AppData\Local\Temp\tmpf5ccz9fv

 

如果想查看是否生成临时文件夹有2个方法:

1、注释tempfile源码中的clean(下图中2个红框所改动的)

 

 

 2、使用tempfile.mkdtemp来创建临时文件夹,只要不删除,就会一直存在

 

mkdtemp

创建临时文件夹,返回临时文件夹的绝对路径,不会自动删除,需要手动删除(使用shutil.rmtree)

mkdtemp(suffix=None, prefix=None, dir=None)

使用了dir参数,将临时文件目录设置为指定的路径,suffix添加后缀,prefix添加前缀

#mkdtemp(suffix=None, prefix=None, dir=None)
#tempfile.mkdtemp创建临时文件夹,只返回临时文件夹的绝对路径,参数
fp_dir = tempfile.mkdtemp(suffix='00',prefix='dir_',dir=r'D:\prj_test')
print(fp_dir)

 

输出:

D:\prj_test\dir_rujin7pa00

 

可以看到指定路径下新建了一个临时文件夹,名称前缀为dir_,后缀为00,并没有自动清楚

 

 如果需要清除只需要使用shutil.rmtree(path)

shutil.rmtree(fp_dir)

 

 

mkstemp

创建临时文件,不会自动清除,需要手动清除,返回包含两个元素的元组,第一个元素表示只是操作该文件的安全级别(文件描述符),第二个元素是该临时文件的路径

mkstemp(suffix=None, prefix=None, dir=None, text=False)

text:指定是否以文本形式打开,否则以二进制打开文件(默认),在某些操作系统没有区别

#tempfile.mkstemp创建临时文件,不会自动清除,需要手动清除,返回包含两个元素的元组,第一个元素表示只是操作该文件的安全级别(文件描述符),第二个元素是该临时文件的路径
#mkstemp(suffix=None, prefix=None, dir=None, text=False)
#suffix:临时文件名称的后缀,prefix:临时文件名称的前缀,dir:指定临时文件所在的目录,如果没有指定目录,将根据系统环境变量TMPDIR,TEMP或者TMP的设置来保存临时文件,text:是否以文本的形式来操作文件,默认为false,以二进制来操作文件
fp1 = tempfile.mkstemp(suffix='1',prefix='a')
print(fp1)
fp1_safety = fp1[0]
fp1_path = fp1[1]
print(fp1_path)
with open(fp1_path,'w+') as f:
    f.write('你好')#.encode('utf-8'))
    f.seek(0)
    print(f.read())#.decode('utf-8'))

os.remove(fp1_path)

 

上面的代码执行,你会发现os.remove并不能将临时文件夹清除,会提示有个程序正在使用此文件

 

 这时候返回的操作该文件的安全级别(文件描述符)就有了用武之地,它同时是个文件描述符,需要将其一起关闭了,才能将临时文件夹移除,完整代码如下:

fp1 = tempfile.mkstemp(suffix='1',prefix='a')
print(fp1)
fp1_safety = fp1[0]
fp1_path = fp1[1]
print(fp1_path)
with open(fp1_path,'w+') as f:
    f.write('你好')#.encode('utf-8'))
    f.seek(0)
    print(f.read())#.decode('utf-8'))
#如要删除临时文件,需要关闭此文件描述符
os.close(fp1_safety)
os.remove(fp1_path)

 

 

 

mktemp(不安全,推荐使用mkstemp)

创建临时文件,返回的是临时文件绝对路径

mktemp() 函数生成一个文件名,然后使用该名称创建一个文件。 这是不安全的,因为另一个进程可能会在调用 mktemp() 和随后尝试通过第一个进程创建文件之间的空隙创建一个同名文件。这意味着应用程序可能加载错误的数据或暴露其他的临时数据

 

 

以上就是tempfile库的常规方法使用,在实际使用当中,可以根据情况选择对应的方法进行临时文件(文件夹创建)以及是否保留临时文件等

 

标签:None,tempfile,创建,fp1,临时文件,dir
From: https://www.cnblogs.com/trystudy/p/16739128.html

相关文章