当前位置: 移动技术网 > IT编程>脚本编程>Python > Python3标准库:tempfile临时文件系统对象

Python3标准库:tempfile临时文件系统对象

2020年03月16日  | 移动技术网IT编程  | 我要评论

美剧天堂网,blue jeans,笑傲江湖未删减版

1. tempfile临时文件系统对象

要想安全的创建名字唯一的临时文件,以防止被试图破坏应用或窃取数据的人猜出,这很有难度。tempfile模块提供了多个函数来安全的创建临时文件系统资源。temporaryfile()打开并返回一个未命名的文件,namedtemporaryfile()打开并返回一个命名文件,spooledtemporaryfile在将内容写入磁盘之前先将其保存在内存中,temporarydirectory是一个上下文管理器,上下文关闭时会删除这个目录。

1.1 临时文件

如果应用需要临时文件来存储数据,而不需要与其他程序共享这些文件,则应当使用temporaryfile()函数创建文件。这个函数会创建一个文件,而且如果平台支持,它会立即断开这个新文件的链接。这样一来,其他程序就不可能找到或打开这个文件,因为文件系统表中根本没有这个文件的引用。对于temporaryfile()创建的文件,无论通过调用close()还是结合使用上下文管理器api和with语句,关闭文件时都会自动删除这个文件。

import os
import tempfile

print('building a filename with pid:')
filename = '/guess_my_name.{}.txt'.format(os.getpid())
with open(filename, 'w+b') as temp:
    print('temp:')
    print('  {!r}'.format(temp))
    print('temp.name:')
    print('  {!r}'.format(temp.name))

# clean up the temporary file yourself.
os.remove(filename)

print()
print('temporaryfile:')
with tempfile.temporaryfile() as temp:
    print('temp:')
    print('  {!r}'.format(temp))
    print('temp.name:')
    print('  {!r}'.format(temp.name))

这个例子展示了采用不同方法创建临时文件的差别,一种做法是使用一个通用模式来构造临时文件的文件名,另一种做法是使用temporaryfile()函数。temporaryfile()返回的文件没有文件名。

默认的,文件句柄是使用模式'w+b'创建的,以便它在所有平台上都表现一致,并允许调用者读写这个文件。 

import os
import tempfile

with tempfile.temporaryfile() as temp:
    temp.write(b'some data')

    temp.seek(0)
    print(temp.read())

写文件之后,必需使用seek()"回转"文件句柄以便从文件读回数据。

要以文本模式打开文件,创建文件时要设置mode为'w+t'。

import tempfile

with tempfile.temporaryfile(mode='w+t') as f:
    f.writelines(['first\n', 'second\n'])

    f.seek(0)
    for line in f:
        print(line.rstrip())

这个文件句柄将把数据处理为文本。

1.2 命名文件

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

import os
import pathlib
import tempfile

with tempfile.namedtemporaryfile() as temp:
    print('temp:')
    print('  {!r}'.format(temp))
    print('temp.name:')
    print('  {!r}'.format(temp.name))

    f = pathlib.path(temp.name)

print('exists after close:', f.exists())

句柄关闭后文件将被删除。

1.3 假脱机文件

如果临时文件中包含的数据相对较少,则使用spooledtemporaryfile可能更高效,因为它使用一个io.bytesio或io.stringio缓冲区在内存中保存内容,直到数据达到一个阈值时,数据将“滚动”并写入磁盘,然后用常规的temporaryfile()替换这个缓冲区。 

import tempfile

with tempfile.spooledtemporaryfile(max_size=100,
                                   mode='w+t',
                                   encoding='utf-8') as temp:
    print('temp: {!r}'.format(temp))

    for i in range(3):
        temp.write('this line is repeated over and over.\n')
        print(temp._rolled, temp._file)

这个例子使用spooledtemporaryfile的私有属性来确定何时滚动到磁盘。除非要调整缓冲区大小,否则很少需要检查这个状态。

要显示的将缓冲区写至磁盘,可以调用rollover()或fileno()方法。 

import tempfile

with tempfile.spooledtemporaryfile(max_size=1000,
                                   mode='w+t',
                                   encoding='utf-8') as temp:
    print('temp: {!r}'.format(temp))

    for i in range(3):
        temp.write('this line is repeated over and over.\n')
        print(temp._rolled, temp._file)
    print('rolling over')
    temp.rollover()
    print(temp._rolled, temp._file)

在这个例子中,由于缓冲区非常大,远远大于实际的数据量,所以除非调用rollover(),否则不会在磁盘上创建任何文件。

1.4 临时目录

需要多个临时文件时,可能更方便的做法是用temporarydirectory创建一个临时目录,并打开该目录中的所有文件。 

import pathlib
import tempfile

with tempfile.temporarydirectory() as directory_name:
    the_dir = pathlib.path(directory_name)
    print(the_dir)
    a_file = the_dir / 'a_file.txt'
    a_file.write_text('this file is deleted.')

print('directory exists after?', the_dir.exists())
print('contents after:', list(the_dir.glob('*')))

上下文管理器会生成目录名,可以在上下文块中用来建立其他文件名。

1.5 临时文件位置

如果没有使用dir参数指定明确的目标位置,则临时文件使用的路径会根据当前平台和设置而变化。tempfile模块包括两个函数来查询运行时使用的设置。

import tempfile

print('gettempdir():', tempfile.gettempdir())
print('gettempprefix():', tempfile.gettempprefix())

gettempdir()返回包含所有临时文件的默认目录,gettempprefix()返回新文件和目录名和字符串前缀。

gettempdir()返回的值根据一个简单算法来设置,它会查找一个位置列表,寻找第一个允许当前进程创建文件的位置。

import tempfile

tempfile.tempdir = '/i/changed/this/path'
print('gettempdir():', tempfile.gettempdir())

如果程序需要对所有临时文件使用一个全局位置,但不使用以上任何环境变量,则应当直接设置tempfile.tempdir,为该变量赋一个值。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网