将BytesIO转换为文件

K E*_*gle 27 python

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

Rei*_*ard 29

因此,如果您提供了用于处理Excel文件的库,那将会更有帮助,但是这里有一大堆解决方案,其中一些可能有效,基于我正在制作的随机假设,因为完全没有样本码:

  • 基于io模块中的第一段,听起来像所有具体类 - 包括BytesIO-都是类文件对象.不知道你到目前为止尝试了什么代码,我不知道你是否尝试将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 
Run Code Online (Sandbox Code Playgroud)
  • 您可能需要检查您用于将BytesIO转换为正确的模块所需的读取器/写入器/包装器类型
  • 我相信我听说过(出于内存原因,由于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
Run Code Online (Sandbox Code Playgroud)

我希望其中一点可以解决你的问题.


Mar*_*oma 29

# 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())
Run Code Online (Sandbox Code Playgroud)

  • `wb` ← 注意 `b`,因为它代表[二进制模式](https://docs.python.org/3/library/functions.html#open) (6认同)

joh*_*son 6

pathlib.Path('file').write_bytes(io.BytesIO(b'data').getbuffer())
Run Code Online (Sandbox Code Playgroud)