Python: simulate writing to a file object without creating a file

不问归期 提交于 2020-05-09 06:03:47

问题


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

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

回答1:


Since the PdfFileMerger.write method supports writing to file-like objects, you can simply make the PdfFileMerger object write to a BytesIO object instead:

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


来源:https://stackoverflow.com/questions/58718938/python-simulate-writing-to-a-file-object-without-creating-a-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!