将BytesIO转换为文件

恩格尔

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

里德·巴拉德(Reid Ballard)

如果您提供了用于处理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 
  • 您可能需要检查用于将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

我希望这些要点之一可以解决您的问题。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章