将cStringIO变量转换为文件

时间:2014-04-16 11:21:37

标签: python xlrd xlwt cstringio

我在cStringIO变量中创建了一个Excel文件。

我需要打开它并阅读它。但是要使用xlrd函数xlrd.open_workbook(excel_file_name)打开excel文件,我需要通过其文件名来调用它。但在这种情况下,没有文件名,因为它是一个包含Excel文件表示的cStrinIO变量。

如何将cStringIO变量转换为可以打开的真实excel文件?

谢谢!

2 个答案:

答案 0 :(得分:2)

看起来xlrd.open_workbook()也接受了file_contents参数,所以可能如下?

xlrd.open_workbook(file_contents=cstringio_var.getvalue())

答案 1 :(得分:1)

您可以使用tempfile.NamedTemporaryFile

示例(未测试):

with tempfile.NamedTemporaryFile() as f:
    f.write(your_cStringIO_variable.read())
    f.flush()
    something = xlrd.open_workbook(f.name)