티스토리 뷰

반응형

Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.

Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.

 

아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.

CSV new-line character seen in unquoted field error

CSV 새 줄 문자가 따옴표로 묶이지 않은 필드에서 발견되었습니다

 문제 내용 

the following code worked until today when I imported from a Windows machine and got this error:

다음 코드는 오늘까지 작동되었으나, 윈도우 머신에서 가져와서 다음 오류가 발생했습니다.

 

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

"unquoted field에서 새 줄 문자가 보입니다 - 파일을 universal-newline 모드로 열어야 하나요?"
import csv

class CSV:


    def __init__(self, file=None):
        self.file = file

    def read_file(self):
        data = []
        file_read = csv.reader(self.file)
        for row in file_read:
            data.append(row)
        return data

    def get_row_count(self):
        return len(self.read_file())

    def get_column_count(self):
        new_data = self.read_file()
        return len(new_data[0])

    def get_data(self, rows=1):
        data = self.read_file()

        return data[:rows]

 

How can I fix this issue?

이 문제를 어떻게 해결할 수 있을까요?
def upload_configurator(request, id=None):
    """
    A view that allows the user to configurator the uploaded CSV.
    """
    upload = Upload.objects.get(id=id)
    csvobject = CSV(upload.filepath)

    upload.num_records = csvobject.get_row_count()
    upload.num_columns = csvobject.get_column_count()
    upload.save()

    form = ConfiguratorForm()

    row_count = csvobject.get_row_count()
    colum_count = csvobject.get_column_count()
    first_row = csvobject.get_data(rows=1)
    first_two_rows = csvobject.get_data(rows=5)

 

 

 높은 점수를 받은 Solution 

It'll be good to see the csv file itself, but this might work for you, give it a try, replace:

CSV 파일 자체를 보는 것이 좋겠지만, 이것이 당신에게 도움이 될 수 있습니다. 시도해보세요. 다음을 대체하세요.
file_read = csv.reader(self.file)

 

with:

다음과 같이 대체해보세요:
file_read = csv.reader(self.file, dialect=csv.excel_tab)

 

Or, open a file with universal newline mode and pass it to csv.reader, like:

또는, 유니버설 개행 모드로 파일을 열고 csv.reader에 전달합니다. 예시 코드는 다음과 같습니다:
reader = csv.reader(open(self.file, 'rU'), dialect=csv.excel_tab)

 

Or, use splitlines(), like this:

또는, splitlines()를 사용하여 다음과 같이 작성할 수 있습니다:
def read_file(self):
    with open(self.file, 'r') as f:
        data = [row for row in csv.reader(f.read().splitlines())]
    return data

 

 

 가장 최근 달린 Solution 

If this happens to you on mac (as it did to me):

만약 이 문제가 맥에서 발생한다면 (제 경우와 같이):

 

  1. Save the file as CSV (MS-DOS Comma-Separated)
  2. Run the following script
  3. with open(csv_filename, 'rU') as csvfile: csvreader = csv.reader(csvfile) for row in csvreader: print ', '.join(row)
1. 파일을 CSV (MS-DOS Comma-Separated) 형식으로 저장하고,
2. 다음 스크립트를 실행합니다.
3. with open(csv_filename, 'rU') as csvfile: csvreader = csv.reader(csvfile) for row in csvreader: print ', '.join(row)

 

 

 

출처 : https://stackoverflow.com/questions/17315635/csv-new-line-character-seen-in-unquoted-field-error

반응형
댓글
공지사항
최근에 올라온 글