我有一个包含excel文档数据的BytesIO对象。我想要使用的库不支持BytesIO,而是需要一个File对象。如何获取BytesIO对象并将其转换为File对象?
答案 0 :(得分:21)
因此,如果您提供了用于处理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
我希望其中一点可以解决你的问题。
答案 1 :(得分:12)
# 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())
答案 2 :(得分:0)
pathlib.Path('file').write_bytes(io.BytesIO(b'data').getbuffer())