将BytesIO转换为文件。

84

我有一个包含Excel文档数据的BytesIO对象。我想要使用的库不支持BytesIO,而是需要一个文件对象。我该如何将我的BytesIO对象转换成一个文件对象?


3
可能是XY问题。您实际上想要做什么?例如,您是否需要支持fileno属性的某些内容? - Mad Physicist
4个回答

80
# 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())

5
wb ← 注意 b,它代表二进制模式 - Denis

47

如果您提供了处理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 
  • 您可能需要检查您正在使用的模块所期望的Reader/Writer/Wrapper类型,以将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

我希望这些建议中的一个能够解决您的问题。


1
read()在BytesIO上不起作用。它会发送垃圾。用户使用getbuffer()。 - Leo
是的,read() 不会返回你想要的内容。不确定这个答案曾经是否正确,但现在你确实需要使用 getbuffer() - Ibrahim

15
pathlib.Path('file').write_bytes(io.BytesIO(b'data').getbuffer())

1
getbuffer() 返回一个 Memoryview。write() 需要 bytes。有什么建议可以抑制这个警告吗?代码可以正常工作,但是还有一些小问题。 - Jari Turkia

3

Python 3.10:

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

它会创建一个名为 "temp_file_name.tmp" 的实际本地文件吗? - yoty66

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接