【问题标题】:new-line character seen in unquoted field在未引用字段中看到的换行符
【发布时间】:2013-07-20 04:38:36
【问题描述】:

我有一个从 Django 表单加载到内存中的文件。它给了我以下错误:

new-line character seen in unquoted field - do you need to open the file in universal-newline mode?

使用了另一个解决方案this。

但是,我已经在内存中有文件,所以我需要将其更改为以"rU" 格式打开。

这是我在views.py中的相关代码

form = ResultsUploadForm(request.POST, request.FILES)
    if form.is_valid():
        form.save()
        reader = csv.reader(request.FILES['file'])
        for row in reader:
            #etc...

有谁知道如何解决这个问题?该语句抛出错误for row in reader:

【问题讨论】:

标签: python django


【解决方案1】:

我在another post找到了解决方案

问题是我如何保存 .csv 文件。在 mac 的 excel 中生成 .csv 文件时,将其保存为“Windows 逗号分隔值 (.csv)” 这将停止添加在 Django 和 python 中抛出 import csv 的不需要的字符。

【讨论】:

    【解决方案2】:

    您可以将读取模式更改为“rU”而不是“r”或“rb”

    【讨论】:

      【解决方案3】:

      这就是我在读取上传的包含一些特殊符号的 CSV 文件时避免上述错误的方法。

      def utf_8_encoder(unicode_csv_data): //encodes the Unicode strings as UTF-8 
          for line in unicode_csv_data:
              yield line.encode('utf-8')
      
      
      def validate_csv(request):
          csv_contents = request.FILES['files'].read().decode('utf-8-sig') // to avoid csv exception while reading unwanted characters (eg: \xef\xbb\xbf)
          request_file = csv_contents.splitlines()
          dict_reader = csv.DictReader(utf_8_encoder(request_file)) // avoid error - ascii' codec can't encode character u'\\ufeff' in position 0: ordinal not in range(128)
          #because data contain some special symobls like G�mez
          fieldnames = dict_reader.fieldnames //fieldnames contain column header
          for item in dict_reader:
              #etc...
      

      【讨论】:

        【解决方案4】:

        检查 csv 文件中的标题行。它应该与列名完全相同。

        【讨论】:

          猜你喜欢
          • 2013-06-23
          • 2013-01-03
          • 2019-09-01
          • 2018-01-26
          • 2013-04-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-11-17
          相关资源
          最近更新 更多