猿问

在 Django 中迭代并验证上传的大型 CSV 文件

我正在使用 Django 模块django-chunked-upload来接收潜在的大型 CSV 文件。我可以假设 CSV 格式正确,但我不能假设分隔符是什么。


上传完成后,将返回一个UploadedFile对象。我需要验证上传的 CSV 中是否包含正确的列,以及每列中的数据类型是否正确。


加载文件csv.reader()不起作用:


reader = csv.reader(uploaded_file)

next(reader)

>>> _csv.Error: iterator should return strings, not bytes (did you open the file in text mode?)

这可能是因为uploaded_file.content_type和uploaded_file.charset都通过 as None。


我想出了一个相当不雅的解决方案来获取标题并遍历行:


i = 0

header = ""

for line in uploaded_file:

    if i == 0:

        header = line.decode('utf-8')

        header_list = list(csv.reader(StringIO(header)))

        print(header_list[0])

        #validate column names

    else:

        tiny_csv = StringIO(header + line.decode('utf-8'))

        reader = csv.DictReader(tiny_csv)

        print(next(reader))

        #validate column types

我还考虑过尝试加载实际保存文件的路径:


path = #figure out the path of the temp file

f = open(path,"r")

reader = csv.reader(f)

但是我无法从 UploadedFile 对象中获取临时文件路径。


理想情况下,我想从 UploadedFile 对象中创建一个普通的阅读器或 DictReader,但它似乎让我望而却步。有人有主意吗?- 谢谢


ITMISS
浏览 90回答 1
1回答
随时随地看视频慕课网APP

相关分类

Python
我要回答