gpt4 book ai didi

python - 打开电子表格返回 InMemoryUploadedFile

转载 作者:太空狗 更新时间:2023-10-29 22:11:39 60 4
gpt4 key购买 nike

我有一个用户将文件上传到网站,我需要解析电子表格。这是我的代码:

input_file = request.FILES.get('file-upload')
wb = xlrd.open_workbook(input_file)

我不断收到的错误是:

TypeError at /upload_spreadsheet/
coercing to Unicode: need string or buffer, InMemoryUploadedFile found

为什么会发生这种情况,我需要做些什么来解决它?谢谢。

作为引用,这是我在 shell 中打开文件的方式

>>> import xlrd
>>> xlrd.open_workbook('/Users/me/dave_example.xls')
<xlrd.Book object at 0x10d9f7390>

最佳答案

您可以在使用 xlrd 打开之前将 InMemoryUploadedFile 转储到临时文件。

try:
fd, tmp = tempfile.mkstemp()
with os.fdopen(fd, 'w') as out:
out.write(input_file.read())
wb = xlrd.open_workbook(tmp)
... # do what you have to do
finally:
os.unlink(tmp) # delete the temp file no matter what

如果你想把所有的东西都保存在内存中,试试:

wb = xlrd.open_workbook(filename=None, file_contents=input_file.read())

关于python - 打开电子表格返回 InMemoryUploadedFile,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12886842/

60 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com