django - 使用 csv.reader 读取上传的文件

标签 django

任务:读取上传的文件以检查结构。我的测试上传文件有 5 行标题和大约 20-30 列。编码为 ISO-8859-1

听起来很简单,但它让我慢慢陷入疯狂。
目前唯一可行的解​​决方案是绕道模型:

file = request.FILES.getlist('job_file', None)[0]
newdoc = models.Jobs(job_file=file)
newdoc.save()
with codecs.open(newdoc.job_file.name, "r", encoding='iso-8859-1') as fp:
    file_content = list(csv.reader(fp, delimiter=';', quotechar='"'))

肮脏,疯狂,远不能接受

非工作解决方案:
1:
file_content = list(csv.reader(file, delimiter=';', quotechar='"'))
print(file_content)
>>>_csv.Error: iterator should return strings, not bytes (did you open the file in text mode?)

2:
file_content = list(csv.reader(file.open('r'), delimiter=';', quotechar='"'))
print(file_content)
>>> TypeError: argument 1 must be an iterator

3:
file_content = list(csv.reader(file.read(), delimiter=';', quotechar='"'))
print(file_content)
>>>_csv.Error: iterator should return strings, not int (did you open the file in text mode?)

一些提示:
print(file.read())
>>>b';"";""\r\n' <-- WRONG see file content at the top
print(file.readlines())
>>>[]

请救救我!

最佳答案

无需打开文件,您可以将上传的文件转换为TextIOWrapper .这是更干净的例子

from io import StringIO

file = request.FILES.getlist('job_file', None)[0]
newdoc = models.Jobs.objects.create(job_file=file)
fp = StringIO(file.read(), encoding='iso-8859-1')
file_content = list(csv.reader(fp, delimiter=';', quotechar='"'))

关于django - 使用 csv.reader 读取上传的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42292773/

相关文章:

javascript - tinyMCE 不添加特定文本区域的控件

Django - 用户 session 显示用户数据

python - Django 日期按月份过滤

python - Django 根据 url 请求预填写表单下拉框

django - 更改 url 中的一个查询参数 (Django)

css - Django 检查请求是否是视网膜设备

python - 如何 Pickle Django 模型

python - 使用 Django 和 MySQL 存储和查找大型 DNA 微阵列结果

python - 添加 "search"同时保持分页和排序?

javascript - 无法将 CSRF token 添加到 Django POST 请求的 XMLhttpRequest