tempfile: Temporary File System Object

Introduction

Want to create a unique temporary file name of security, in order to prevent attempts to destroy or steal data applications people guessed, this is very difficult. tempfile module provides several functions to create a temporary file system security resources. TemporaryFile function opens and returns an unnamed file, NamedTemporaryFile open file and returns the name, SpooledTemporaryFile before the file is written to disk to save it first in memory, TemporaryDirectory is a context manager, this directory will be deleted when the context is closed, Here we are introduced one by one

Temporary Files

import tempfile

'''
如果应用需要临时文件来存储数据,而不需要与其他程序共享这些文件,则应当使用TemporaryFile函数来创建文件。
这个函数会创建一个文件,而且如果平台支持,它会立即断开这个新文件的链接。
这样一来,其他程序就不可能找到或者打开这个文件,因为文件系统表中根本没有这个文件的引用。
对于TemporaryFile函数创建的文件,不论通过调用close函数,还是结合使用上下文管理器API、with语句,关闭文件时都会自动删除这个临时文件
'''
# mode:默认是w+b,二进制形式。这里使用w+,可读可写
with tempfile.TemporaryFile(mode="w+", encoding="utf-8") as tmp:
    print(tmp)  # <tempfile._TemporaryFileWrapper object at 0x0000000002372A20>
    # 随机生成的名字,但是我们是不需要指定名字的
    print(tmp.name)  # C:\Users\satori\AppData\Local\Temp\tmpouzkbg3b
    print(tmp.mode)  # w+

with tempfile.TemporaryFile(mode="w+", encoding="utf-8") as tmp:
    tmp.write("这是一个临时文件,里面存储了内容")
    # 注意文件写完之后,指针移到了末尾,要想读取的话,需要将指针移到行首
    tmp.seek(0)
    print(tmp.read())  # 这是一个临时文件,里面存储了内容

Name the file

import tempfile
import pathlib
 
 
'''
有些情况下,可能非常需要一个命名的临时文件。对于跨多个进程甚至主机的应用来说,为文件命名是在应用的不同部分之间传递文件的最简单的办法
NamedTemporaryFile函数会创建一个文件,但不会断开它的链接,所以会保留它的文件名(用name属性访问)
但是注意在Windows上NamedTemporaryFile和TemporaryFile是一样的

if _os.name != 'posix' or _os.sys.platform == 'cygwin':
    # On non-POSIX and Cygwin systems, assume that we cannot unlink a file
    # while it is open.
    TemporaryFile = NamedTemporaryFile
'''
with tempfile.NamedTemporaryFile() as tmp:
    print(tmp.name)  # C:\Users\EDZ\AppData\Local\Temp\tmp3gg7iiir
    f = pathlib.Path(tmp.name)
    print(f.exists())  # True
 
# 句柄关闭后,文件也将被删除
print(f.exists())  # False
# 所以在Windows上,NamedTemporaryFile和TemporaryFile是没有差别的

Spooled files

import tempfile

'''
如果临时文件中包含的数据相对较少,则使用SpooledTemporaryFile函数可能更高效,因为它使用一个io.BytesIO或io.StringIO缓冲区在内存中保存内容,直到数据达到一个阈值大小。
当数据量超过这个阈值时,数据将滚动并写入磁盘,然后用常规的TemporaryFile替换这个缓冲区
'''
with tempfile.SpooledTemporaryFile(max_size=40, mode="w+", encoding="utf-8") as f:
    for i in range(4):
        f.write("这一行会被反复不断地写哦")
        print(f._rolled, f._file)
'''
False <_io.StringIO object at 0x00000000021E90D8>
False <_io.StringIO object at 0x00000000021E90D8>
False <_io.StringIO object at 0x00000000021E90D8>
True <tempfile._TemporaryFileWrapper object at 0x0000000002972BA8>
'''
# 如果要显示地将缓冲区里面的数据写入磁盘,可以调用rollover或者fileno函数

Temporary directory

If you need multiple temporary files, it may be more convenient to use TemporaryDirectory is to create a temporary directory, and open all files in a directory, but not commonly used

Temporary File Location

import tempfile

'''
在创建临时文件,可以指定dir,即临时文件的生成路径。如果没有指定dir的话,那么临时文件的存储路径会根据当前平台的不同而不同。
tempfile模块包含两个函数,可以用来查询运行时使用的设置
'''
# 返回包含所有临时文件的默认目录
print(tempfile.gettempdir())  # C:\Users\satori\AppData\Local\Temp
# 返回新文件和目录名的字符串前缀
print(tempfile.gettempprefix())  # tmp

Guess you like

Origin www.cnblogs.com/traditional/p/11874681.html