我有一个包含Excel文档数据的BytesIO对象。我要使用的库不支持BytesIO,而是需要一个File对象。如何获取BytesIO对象并将其转换为File对象?
最佳答案
如果您提供了用于处理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
我希望这些要点之一可以解决您的问题。关于python - 将BytesIO转换为文件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29324037/