Python:模拟写入文件对象而不创建文件
Python: simulate writing to a file object without creating a file
我正在使用 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()
由于 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()
我正在使用 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()
由于 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()