首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >将BytesIO转换为文件

将BytesIO转换为文件
EN

Stack Overflow用户
提问于 2015-03-29 07:56:01
回答 3查看 81.4K关注 0票数 49

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

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2016-06-23 12:52:26

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

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

代码语言:javascript
运行
复制
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转换为正确的
  • 我相信我听说过(由于内存原因,由于excel文件非常大) excel模块不会加载整个文件。如果这最终意味着您需要的是磁盘上的物理文件,那么您可以轻松地临时写入Excel文件,并在完成后将其删除。示例:

代码语言:javascript
运行
复制
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

我希望这些观点中的一个能解决你的问题。

票数 40
EN

Stack Overflow用户

发布于 2020-02-28 19:05:02

代码语言:javascript
运行
复制
# 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())
票数 32
EN

Stack Overflow用户

发布于 2020-03-06 20:07:58

代码语言:javascript
运行
复制
pathlib.Path('file').write_bytes(io.BytesIO(b'data').getbuffer())
票数 8
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29324037

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档