[英]Python: simulate writing to a file object without creating a file
I'm working with Python3 and I want to simulate writing to a file, but without actually creating a file.我正在使用 Python3,我想模拟写入文件,但没有实际创建文件。
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.我认为
StringIO
是这种情况的一个很好的候选者,但我不知道在这种情况下如何使用它,这将写入 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()
Since the PdfFileMerger.write
method supports writing to file-like objects, you can simply make the PdfFileMerger
object write to a BytesIO
object instead:由于
PdfFileMerger.write
方法支持写入类似文件的对象,您可以简单地将PdfFileMerger
object 写入BytesIO
object :
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.