【发布时间】:2015-03-28 23:56:01
【问题描述】:
我有一个包含 excel 文档数据的 BytesIO 对象。我要使用的库不支持BytesIO,而是需要一个 File 对象。如何获取我的 BytesIO 对象并将其转换为 File 对象?
【问题讨论】:
-
可能的 XY 问题。你到底想做什么。例如,您是否需要支持
fileno属性的东西?
标签: python
我有一个包含 excel 文档数据的 BytesIO 对象。我要使用的库不支持BytesIO,而是需要一个 File 对象。如何获取我的 BytesIO 对象并将其转换为 File 对象?
【问题讨论】:
fileno 属性的东西?
标签: python
# 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())
【讨论】:
如果您提供用于处理 excel 文件的库会很有帮助,但这里有一些解决方案,基于我所做的一些假设:
.
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
.
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() 不会返回你想要的。不确定这个答案是否曾经正确,但您现在确实想使用getbuffer()。
pathlib.Path('file').write_bytes(io.BytesIO(b'data').getbuffer())
【讨论】:
Python 3.10:
pathlib.Path('temp_file_name.tmp').write_bytes(io.BytesIO(b'data').getbuffer().tobytes())
【讨论】: