我有一个包含excel文档数据的BytesIO对象。我要使用的库不支持BytesIO,需要一个文件对象。如何获取BytesIO对象并将其转换为文件对象?
发布于 2016-06-23 12:52:26
如果你提供了用来处理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
我希望这些观点中的一个能解决你的问题。
发布于 2020-02-28 19:05:02
# 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())
发布于 2020-03-06 20:07:58
pathlib.Path('file').write_bytes(io.BytesIO(b'data').getbuffer())
https://stackoverflow.com/questions/29324037
复制相似问题