将Django文件上载对象提供给Python CSV模块的意外结果 [英] Unexpected results feeding Django File upload object to Python CSV module
问题描述
我没有问题让文件上传,如果我保存到磁盘,所有的格式化是完整的。
我写了一个函数读取文件在Django中使用:
data = csv.reader(f.read())
其中f是我从'form.cleaned_data ['file']'获得的Django文件对象,并且是文件已绑定到表单。
当我尝试使用
读取文件in data:
logging.debug(row)
我得到一个意想不到的结果,似乎是生产小包的数据几乎就好像它读取一些缓冲区。例如,对于我的浮动字段,当我记录每一行时,我得到这个:
['0'] ['。'] ['0'] ['5' ] ['',''] ['0'] ['。'] ['2'] etc等...其中方括号之间的每个项实际上来自一行(即换行)
csv.reader需要它支持迭代器协议的对象,我相信Django File对象
那么我做错了什么?
<你实际上是把错误的可迭代传递给
csv.reader()
。尝试将该行更改为: data = csv.reader(f)
你所做的是将文件的全部内容传递给 csv.reader()
函数,这将导致它迭代每个单独的字符,将它们作为一个单独的行。如果你将实际的文件对象传递给函数,它将按照你所期望的那样迭代该文件中的行。
I have no problems getting the file to upload and if I save it to disk, all formatting is intact.
I wrote a function to read in the the file within Django using:
data = csv.reader(f.read())
where f is the Django file object that I get from 'form.cleaned_data['file']' and yes the file is already bound to the form.
When I try to read the file using
for row in data:
logging.debug(row)
I get an unexpected result in that it appears to be producing small packs of the data almost as if its reading some buffer. for example, for my float fields I get this when I log each row:
['0'] ['.'] ['0'] ['5']['', ''] ['0'] ['.'] ['2'] etc etc... where each item between the square bracket is actually from one row (ie. a newline)
csv.reader requires the object it takes to support the iterator protocol which I believe the Django File object does
So what am I doing wrong?
You're actually passing the wrong iterable to csv.reader()
. Try changing that line to:
data = csv.reader(f)
What you're doing is passing the whole contents of the file to the csv.reader()
function, which will cause it to iterate over every individual character, treating each of them as a separate line. If you pass the actual file object to the function, it will iterate over the lines in that file, as you expect.
这篇关于将Django文件上载对象提供给Python CSV模块的意外结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!