programing tip

CSV 리더 (Python)의 "줄에 NULL 바이트 포함"

itbloger 2020. 10. 19. 07:49
반응형

CSV 리더 (Python)의 "줄에 NULL 바이트 포함"


.CSV 파일 (input.csv)을보고 텍스트 파일 (output.txt)에 나열된대로 특정 요소 (corrected.csv)로 시작하는 행만 다시 쓰는 프로그램을 작성하려고합니다.

지금 내 프로그램은 다음과 같습니다.

import csv

lines = []
with open('output.txt','r') as f:
    for line in f.readlines():
        lines.append(line[:-1])

with open('corrected.csv','w') as correct:
    writer = csv.writer(correct, dialect = 'excel')
    with open('input.csv', 'r') as mycsv:
        reader = csv.reader(mycsv)
        for row in reader:
            if row[0] not in lines:
                writer.writerow(row)

안타깝게도이 오류가 계속 발생하며 그에 대한 단서가 없습니다.

Traceback (most recent call last):
  File "C:\Python32\Sample Program\csvParser.py", line 12, in <module>
    for row in reader:
_csv.Error: line contains NULL byte

여기 에있는 모든 사람들 이 저를이 지점까지 데려다 준 것에 감사합니다.


더 쉬운 솔루션으로 비슷한 문제를 해결했습니다.

import codecs
csvReader = csv.reader(codecs.open('file.csv', 'rU', 'utf-16'))

키는 코덱 모듈을 사용하여 UTF-16 인코딩으로 파일을 열었습니다. 더 많은 인코딩이 있습니다 . 문서를 확인하십시오 .


input.csv에 NUL 바이트가 있다고 생각합니다. 당신은 그것을 테스트 할 수 있습니다

if '\0' in open('input.csv').read():
    print "you have null bytes in your input file"
else:
    print "you don't"

만약 그렇다면

reader = csv.reader(x.replace('\0', '') for x in mycsv)

주위를 둘러 볼 수 있습니다. 또는 .csv 파일에 utf16 또는 '흥미로운'무언가가 있음을 나타낼 수 있습니다.


존재하지 않는 척하고 싶다면 생성기를 인라인하여 null 값을 필터링 할 수 있습니다. 물론 이것은 null 바이트가 실제로 인코딩의 일부가 아니며 실제로 일종의 잘못된 아티팩트 또는 버그라고 가정합니다.

(line.replace('\0','') for line in f)아래를 참조하십시오 rb. mode를 사용하여 해당 파일을 열고 싶을 수도 있습니다 .

import csv

lines = []
with open('output.txt','r') as f:
    for line in f.readlines():
        lines.append(line[:-1])

with open('corrected.csv','w') as correct:
    writer = csv.writer(correct, dialect = 'excel')
    with open('input.csv', 'rb') as mycsv:
        reader = csv.reader( (line.replace('\0','') for line in mycsv) )
        for row in reader:
            if row[0] not in lines:
                writer.writerow(row)

이것은 어떤 라인이 문제인지 알려줄 것입니다.

import csv

lines = []
with open('output.txt','r') as f:
    for line in f.readlines():
        lines.append(line[:-1])

with open('corrected.csv','w') as correct:
    writer = csv.writer(correct, dialect = 'excel')
    with open('input.csv', 'r') as mycsv:
        reader = csv.reader(mycsv)
        try:
            for i, row in enumerate(reader):
                if row[0] not in lines:
                   writer.writerow(row)
        except csv.Error:
            print('csv choked on line %s' % (i+1))
            raise

아마도 daniweb의 이것이 도움이 될 것입니다.

csv 파일에서 읽을 때 "Runtime Error! line contains NULL byte"라는 오류가 발생합니다. 이 오류의 근본 원인에 대해 아십니까?

...

Ok, I got it and thought I'd post the solution. Simply yet caused me grief... Used file was saved in a .xls format instead of a .csv Didn't catch this because the file name itself had the .csv extension while the type was still .xls


If you want to replace the nulls with something you can do this:

def fix_nulls(s):
    for line in s:
        yield line.replace('\0', ' ')

r = csv.reader(fix_nulls(open(...)))

A tricky way:

If you develop under Lunux, you can use all the power of sed:

from subprocess import check_call, CalledProcessError

PATH_TO_FILE = '/home/user/some/path/to/file.csv'

try:
    check_call("sed -i -e 's|\\x0||g' {}".format(PATH_TO_FILE), shell=True)
except CalledProcessError as err:
    print(err)    

The most efficient solution for huge files.

Checked for Python3, Kubuntu


I've recently fixed this issue and in my instance it was a file that was compressed that I was trying to read. Check the file format first. Then check that the contents are what the extension refers to.


Turning my linux environment into a clean complete UTF-8 environment made the trick for me. Try the following in your command line:

export LC_ALL=en_US.UTF-8
export LANG=en_US.UTF-8
export LANGUAGE=en_US.UTF-8

pandas.read_csv now handles the different UTF encoding when reading/writing and therefore can deal directly with null bytes

data = pd.read_csv(file, encoding='utf-16')

see https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html

참고URL : https://stackoverflow.com/questions/7894856/line-contains-null-byte-in-csv-reader-python

반응형