【发布时间】:2019-11-05 20:24:54
【问题描述】:
我正在使用 Python3,我想模拟写入文件,但没有实际创建文件。
比如我的具体情况如下:
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 对象。它看起来像这样:
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()
【问题讨论】:
-
我不明白你的问题
-
另外,这不是 Python 3,而是 Python 2
-
@roganjosh 我认为在 Python 中有“类似文件的对象”,它使我们能够模拟处理文件,但不必实际创建一个真实的文件。
StringIO允许我们通过创建缓冲区来处理这些类似文件的对象。我在问通过使用类似文件的对象来模拟写入文件的方法是什么。