I have a module which asks the user to give a csv file, with the binary field. So once the module has it, I decode it and write the result in a Temporary File, but then I can't open it as a CSV file : I will get the error "TypeError: coercing to Unicode: need string or buffer, file found" because I'm trying to open a File Object. So how can I decode the file and then open it as a CSV file ?
我有一个模块,要求用户提供一个带有二进制字段的csv文件。所以一旦模块有它,我解码它并将结果写入临时文件,但是我无法将其作为CSV文件打开:我将得到错误“TypeError:强制转换为Unicode:需要字符串或缓冲区,文件发现“因为我正在尝试打开文件对象。那么如何解码文件然后将其作为CSV文件打开?
Here is my code :
这是我的代码:
# -*- coding: utf-8 -*-
from osv import fields, osv
import csv
import base64
from tempfile import TemporaryFile
class set_dates(osv.osv_memory):
_name = "set.dates"
_columns = {
"donnees": fields.binary("Données", required=True)
}
def do_set(self, cr, uid, ids, data, context=None):
this = self.browse(cr, uid, ids[0])
fileobj = TemporaryFile('w+')
fileobj.write(base64.decodestring(this.donnees))
fic = csv.reader(open(fileobj, "rb"))
tab = list(fic)
#...
Thanks in advance for your help !
在此先感谢您的帮助 !
1 个解决方案
#1
The error is on the line fic = csv.reader(open(fileobj, "rb"))
错误在fic = csv.reader(open(fileobj,“rb”))行上
open()
is complaining that its argument is a file object, instead of a string or buffer. That's because the variable fileobj
is a file
object, which was open with:
open()抱怨它的参数是文件对象,而不是字符串或缓冲区。那是因为变量fileobj是一个文件对象,它打开了:
fileobj = TemporaryFile('w+')
fileobj = TemporaryFile('w +')
You just have to replace:fic = csv.reader(open(fileobj, "rb"))
with:fic = csv.reader(fileobj)
你只需要用:fic = csv.reader(fileobj)替换:fic = csv.reader(open(fileobj,“rb”))
#1
The error is on the line fic = csv.reader(open(fileobj, "rb"))
错误在fic = csv.reader(open(fileobj,“rb”))行上
open()
is complaining that its argument is a file object, instead of a string or buffer. That's because the variable fileobj
is a file
object, which was open with:
open()抱怨它的参数是文件对象,而不是字符串或缓冲区。那是因为变量fileobj是一个文件对象,它打开了:
fileobj = TemporaryFile('w+')
fileobj = TemporaryFile('w +')
You just have to replace:fic = csv.reader(open(fileobj, "rb"))
with:fic = csv.reader(fileobj)
你只需要用:fic = csv.reader(fileobj)替换:fic = csv.reader(open(fileobj,“rb”))