如何在Python中处理多个临时文件序列?

2024-04-20 03:45:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我想通过以下步骤:

1)tempfileA(注:这是从Google云存储下载的blob)

2)tempfileB=函数(tempfileA)

3)tempfileC=函数(tempfileB)

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

到目前为止,我已经从docs找到了下面的示例,但是Temporaryfilewith子句的出口处关闭,因此在下一步中不可能访问临时文件。在

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

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


Tags: 文件方法函数示例docs顺序withgoogle
2条回答

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

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]))

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

with TemporaryFile() as fp0, TemporaryFile() as fp1, TemporaryFile() as fp2:
    fp0.write(b'foo')
    fp0.seek(0)
    fp1.write(fp0.read())
    ...

相关问题 更多 >