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

后端 未结 1 1223
灰色年华
灰色年华 2021-01-21 00:27

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:



        
相关标签:
1条回答
  • 2021-01-21 01:00

    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()
    
    0 讨论(0)
提交回复
热议问题