简体   繁体   English

在未引用的字段中看到的新行字符

[英]new-line character seen in unquoted field

I have a file loaded in memory from a Django form. 我有一个从Django表单加载到内存中的文件。 It is giving me the following error: 它给了我以下错误:

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

Another solution used this . 另一种解决方案使用

However, i already have the file in memory so i require to change it to opening in "rU" format. 但是,我已经将文件存储在内存中,因此我需要将其更改为以"rU"格式打开。

This is my relevant code in views.py 这是我在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...

Does anyone know how to go about fixing this? 有谁知道如何解决这个问题? The error is thrown from this statement for row in reader: for row in reader:此语句抛出错误for row in reader:

I found the solution in another post 我在另一篇文章中找到了解决方案

The issue was how i was saving the .csv file. 问题是我如何保存.csv文件。 When producing a .csv file in excel for mac save it as "Windows Comma Separated Values (.csv)" This will stop the addition of unwanted characters that throw of import csv in Django and python. 在excel for mac中生成.csv文件时,将其保存为“Windows逗号分隔值(.csv)”这将停止在Django和python中添加import csv的不需要的字符。

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

This is how I avoided the above error while reading from the uploaded CSV file that contains some special symbols also. 这是我从上传的包含一些特殊符号的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...

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM