Python:模拟写入文件对象而不创建文件 [英] Python: simulate writing to a file object without creating a file

查看:223
本文介绍了Python:模拟写入文件对象而不创建文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Python3,我想模拟对文件的写入,但是没有实际创建文件.

I'm working with Python3 and I want to simulate writing to a file, but without actually creating a file.

例如,我的具体情况如下:

For example, my specific case is as follows:

merger = PdfFileMerger()

for pdf in files_to_merge:
    merger.append(pdf)

merger.write('result.pdf')  # This creates a file. I want to avoid this
merger.close()

# pdf -> binary
with open('result.pdf', mode='rb') as file:  # Conversely. I don't want to read the data from an actual file
    file_content = file.read()

我认为StringIO是这种情况的很好的选择,但是在这种情况下,我不知道如何使用它,这将写入StringIO对象.看起来像这样:

I think StringIO is a good candidate for this situation, but I don't know how to use it in this case, which would be writing to a StringIO object. It would look something like this:

output = StringIO()
output.write('This goes into the buffer. ')

# Retrieve the value written
print output.getvalue()

output.close() # discard buffer memory

# Initialize a read buffer
input = StringIO('Inital value for read buffer')

# Read from the buffer
print input.read()

推荐答案

由于 PdfFileMerger.write 方法支持写入类似文件的对象,您可以简单地使PdfFileMerger对象写入BytesIO对象:

from io import BytesIO

merger = PdfFileMerger()

for pdf in files_to_merge:
    merger.append(pdf)

output = BytesIO()
merger.write(output)
merger.close()

file_content = output.getvalue()

这篇关于Python:模拟写入文件对象而不创建文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆