任务:读取上传的文件以检查结构。我的测试上传文件有 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/