zoukankan      html  css  js  c++  java
  • Python3标准库:tempfile临时文件系统对象

    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
    ', 'second
    '])
    
        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.
    ')
            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.
    ')
            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,为该变量赋一个值。

  • 相关阅读:
    一本通 1297:公共子序列
    【未完】一本通 1277:【例9.21】方格取数
    一本通 1295:装箱问题
    一本通 1268:【例9.12】完全背包问题
    【BZOJ4416】阶乘字符串(SHOI2013)-状压DP
    【BZOJ2658】小蓝的好友(ZJOI2012)-扫描线+Treap
    【BZOJ2159】Crash的文明世界-第二类斯特林数+树形DP
    【HDU4336】Card Collector-Min-Max容斥
    【BZOJ3997】组合数学(TJOI2015)-Dilworth定理+DP
    【LOJ2537】Minimax(PKUWC2018)-树形DP+线段树合并
  • 原文地址:https://www.cnblogs.com/liuhui0308/p/12464003.html
Copyright © 2011-2022 走看看