如何在Python中处理一系列的多个临时文件?

gor*_*rka 5 python temporary-files python-3.x google-cloud-storage google-cloud-platform

我想执行以下步骤:

1) tempfileA(注意:这是从 Google Cloud Storage 下载的 blob)

2) 临时文件B = 函数(临时文件A)

3) 临时文件C = 函数(临时文件B)

这应该非常简单,但是,我不确定访问基于前一个文件按顺序创建的不同临时文件的最佳方法是什么。

到目前为止,我已经从docs找到了下面的示例,但是Temporaryfile在子句的退出处关闭了with,因此在下一步中应该无法访问临时文件。

# create a temporary file using a context manager
with tempfile.TemporaryFile() as fp:
     fp.write(b'Hello world!')
     fp.seek(0)
     fp.read()
Run Code Online (Sandbox Code Playgroud)

您能否建议实现上述目标的好方法是什么?请注意,在每个步骤中都会调用外部库中的方法来处理当前临时文件,结果应该是下一个临时文件。

Håk*_*Lid 7

您可以在同with一块中打开多个文件。

with TemporaryFile() as fp0, TemporaryFile() as fp1, TemporaryFile() as fp2:
    fp0.write(b'foo')
    fp0.seek(0)
    fp1.write(fp0.read())
    ...
Run Code Online (Sandbox Code Playgroud)


a_g*_*est 6

您可以使用 aTemporaryDirectory并在其中手动创建文件。例如:

import os
import tempfile

def process_file(f_name):
    with open(f_name) as fh:
        return fh.read().replace('foo', 'bar')

with tempfile.TemporaryDirectory() as td:
    f_names = [os.path.join(td, f'file{i}') for i in range(2)]
    with open(f_names[0], 'w') as fh:
        fh.write('this is the foo file')
    with open(f_names[1], 'w') as fh:
        fh.write(process_file(f_names[0]))
Run Code Online (Sandbox Code Playgroud)