【问题标题】:django -how to read uploaded csv file which one field contain '\n'django - 如何读取上传的 csv 文件,其中一个字段包含 '\n'
【发布时间】:2017-04-18 15:35:30
【问题描述】:

当我尝试读取一个字段包含“\n”字符的上传 csv 文件时遇到问题。例如我有一个 csv 文件,它的内容是这样的:

  • 第 1 行:“一个”,“这是\nsample”,
  • 第 2 行:“两个”、“这也是\nsample”

我可以在 request.FILES 中成功获取上传的文件,但是当我循环文件时,该行会因为 '\n' 字符而分解。我的代码是:

file = request.FILES.get('filename', None)
for line in file:
    if line:
        line = line.decode("utf-8")
        fields_set = list(csv.reader([line], skipinitialspace=True))[0]

在第一个循环中,变量'line'的内容是:"one, this is"。在第二个循环中,变量'line' 得到值“sample”。但我想要的是得到'一个,“这是\nsample”'。 任何帮助表示感谢,在此先感谢。

【问题讨论】:

    标签: python django csv


    【解决方案1】:

    您没有正确使用 csv.reader。使用它代替文件阅读器(for line in file 行)

    csvfile = request.FILES.get('filename', None)
    readCSV = csv.reader(csvfile, delimiter=',')
    for row in readCSV:
        print(row)
    

    【讨论】:

    • 使用csv.reader直接读取csvfile会弹出错误“iterator should return strings, not bytes (你是用文本模式打开文件吗?)”
    • 然后让迭代器返回字符串。由于 Django InMemoryUploadedFile 返回的是字节,而不是字符串,因此没有为这种情况适当地定义 csv 阅读器。您需要执行f = csv.reader((x.decode('latin1') for x in csvfile.readlines())) 之类的操作才能将行转换为字符串。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-11
    • 1970-01-01
    • 2017-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多