【问题标题】:Python: simulate writing to a file object without creating a filePython:模拟写入文件对象而不创建文件
【发布时间】: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 允许我们通过创建缓冲区来处理这些类似文件的对象。我在问通过使用类似文件的对象来模拟写入文件的方法是什么。

标签: python stringio


【解决方案1】:

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

【讨论】:

  • 谢谢@blhsing!但我收到此错误:TypeError: string argument expected, got 'bytes' 尝试执行 merger.write(output) 时。
  • 我明白了。我忘记了 PDF 文件是二进制文件,因此您必须使用 io.BytesIO 而不是 io.StringIO
  • 好的,不用担心,我通过output.getvalue() 以更方便的方式处理了阅读
  • 是的。正要写那个。无论如何,我已经相应地更新了我的答案。很高兴能帮上忙。
  • 我也在使用PdfFileMerger,但就我而言,我想执行所有 PDF 合并,而不会对本地文件系统有任何持久性(最后,它被运送到 S3 位置)。对答案稍作调整,效果很好!
猜你喜欢
  • 1970-01-01
  • 2016-03-19
  • 1970-01-01
  • 2021-06-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多