【问题标题】:Convert BytesIO into File将 BytesIO 转换为文件
【发布时间】:2015-03-28 23:56:01
【问题描述】:

我有一个包含 excel 文档数据的 BytesIO 对象。我要使用的库不支持BytesIO,而是需要一个 File 对象。如何获取我的 BytesIO 对象并将其转换为 File 对象?

【问题讨论】:

  • 可能的 XY 问题。你到底想做什么。例如,您是否需要支持 fileno 属性的东西?

标签: python


【解决方案1】:
# Create an example
from io import BytesIO
bytesio_object = BytesIO(b"Hello World!")

# Write the stuff
with open("output.txt", "wb") as f:
    f.write(bytesio_object.getbuffer())

【讨论】:

    【解决方案2】:

    如果您提供用于处理 excel 文件的库会很有帮助,但这里有一些解决方案,基于我所做的一些假设:

    • 根据io module's documentation 中的第一段,听起来所有具体类(包括BytesIO)都是file-like objects。在不知道您到目前为止尝试过什么代码的情况下,我不知道您是否尝试过将 BytesIO 传递给您正在使用的模块。
    • 万一不起作用,您可以简单地将 BytesIO 转换为另一个 io Writer/Reader/Wrapper,方法是将其传递给构造函数。示例:

    .

    import io
    
    b = io.BytesIO(b"Hello World") ## Some random BytesIO Object
    print(type(b))                 ## For sanity's sake
    with open("test.xlsx") as f: ## Excel File
        print(type(f))           ## Open file is TextIOWrapper
        bw=io.TextIOWrapper(b)   ## Conversion to TextIOWrapper
        print(type(bw))          ## Just to confirm 
    
    • 您可能需要检查用于将 BytesIO 转换为正确的模块所需的 Reader/Writer/Wrapper
    • 我相信我听说过(由于内存原因,由于 excel 文件非常大)excel 模块不会加载整个文件。如果这最终意味着您需要的是磁盘上的物理文件,那么您可以轻松地临时写入 Excel 文件,并在完成后将其删除。示例:

    .

    import io
    import os
    
    with open("test.xlsx",'rb') as f:
        g=io.BytesIO(f.read())   ## Getting an Excel File represented as a BytesIO Object
    temporarylocation="testout.xlsx"
    with open(temporarylocation,'wb') as out: ## Open temporary file as bytes
        out.write(g.read())                ## Read bytes into file
    
    ## Do stuff with module/file
    os.remove(temporarylocation) ## Delete file when done
    

    我希望其中一点能解决您的问题。

    【讨论】:

    • read() 在 BytesIO 上不起作用。它发送垃圾。用户 getbuffer().
    • 是的,read() 不会返回你想要的。不确定这个答案是否曾经正确,但您现在确实想使用getbuffer()
    【解决方案3】:
    pathlib.Path('file').write_bytes(io.BytesIO(b'data').getbuffer())
    

    【讨论】:

      【解决方案4】:

      Python 3.10:

      pathlib.Path('temp_file_name.tmp').write_bytes(io.BytesIO(b'data').getbuffer().tobytes())
      

      【讨论】:

        猜你喜欢
        • 2018-01-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-15
        • 2015-02-17
        • 2013-07-27
        相关资源
        最近更新 更多