As @S.Lott says, you should be opening your files in ‘rb’ mode, not ‘rU’ mode. However that may NOT be causing your current problem. As far as I know, using ‘rU’ mode would mess you up if there are embedded r
in the data, but not cause any other dramas. I also note that you have several files (all opened with ‘rU’ ??) but only one causing a problem.
If the csv module says that you have a «NULL» (silly message, should be «NUL») byte in your file, then you need to check out what is in your file. I would suggest that you do this even if using ‘rb’ makes the problem go away.
repr()
is (or wants to be) your debugging friend. It will show unambiguously what you’ve got, in a platform independant fashion (which is helpful to helpers who are unaware what od
is or does). Do this:
print repr(open('my.csv', 'rb').read(200)) # dump 1st 200 bytes of file
and carefully copy/paste (don’t retype) the result into an edit of your question (not into a comment).
Also note that if the file is really dodgy e.g. no r or n within reasonable distance from the start of the file, the line number reported by reader.line_num
will be (unhelpfully) 1. Find where the first x00
is (if any) by doing
data = open('my.csv', 'rb').read()
print data.find('x00')
and make sure that you dump at least that many bytes with repr or od.
What does data.count('x00')
tell you? If there are many, you may want to do something like
for i, c in enumerate(data):
if c == 'x00':
print i, repr(data[i-30:i]) + ' *NUL* ' + repr(data[i+1:i+31])
so that you can see the NUL bytes in context.
If you can see x00
in the output (or in your
od -c
output), then you definitely have NUL byte(s) in the file, and you will need to do something like this:
fi = open('my.csv', 'rb')
data = fi.read()
fi.close()
fo = open('mynew.csv', 'wb')
fo.write(data.replace('x00', ''))
fo.close()
By the way, have you looked at the file (including the last few lines) with a text editor? Does it actually look like a reasonable CSV file like the other (no «NULL byte» exception) files?
- the CSV File Format
- Create a CSV File in Python
- the
_csv.Error: line contains NULL byte
Error in Python - Fix the
_csv.Error: line contains NULL byte
Error in Python - Conclusion
A CSV file is a text file that contains comma-separated values. Each line in the file represents a row of data, and a comma separates each value.
CSV files are often used to store data from spreadsheets or databases. They can be opened in text editors or spreadsheet programs and easily parsed and processed with programming languages.
the CSV File Format
A CSV file is a text file that stores data in a tabular format. Each row of the table is called a record, and each field in the record is called a column.
CSV files typically use a comma to separate each field, but other characters, such as tabs or spaces, can also be used.
CSV files are often used to store data from databases or spreadsheets. They can be opened in a text editor, such as Microsoft Notepad, or a spreadsheet program, such as Microsoft Excel.
Create a CSV File in Python
CSV stands for comma-separated values, where the data in the file is separated with commas and stored in a tabular format as plain text. Each row in the file represents a record, and the column represents the different attributes of the data in the CSV files.
import csv
meta_data = ['First Name', 'Last Name', 'Course', 'Age']
student_data = ['Zeeshan', "Afridi", "Computer programming", '24']
with open('countries.csv', 'w', encoding='UTF8') as f:
writer = csv.writer(f)
# write the header
writer.writerow(meta_data)
# write the data
writer.writerow(student_data)
# closing the file
f.close()
a = open('countries.csv', 'r')
print(a.read())
# closing the file
a.close()
Output:
First Name,Last Name,Course,Age
Zeeshan,Afridi,Computer programming,24
the _csv.Error: line contains NULL byte
Error in Python
Suppose you get _csv.Error: line contains NULL byte
when trying to read a CSV file, it’s likely because there are one or more NULL bytes in the file. To fix this, you can use the --zero-terminated
option when running the CSV reader, which will treat all NULL bytes as end-of-line characters.
When you have any null values, you will encounter the below error:
file my.csv, line 1: line contains NULL byte
Fix the _csv.Error: line contains NULL byte
Error in Python
You encounter _csv.Error: line contains NULL byte
usually because you are trying to read a CSV file saved in the wrong encoding. You must specify the correct encoding when reading the file to fix this.
For example, if the file is encoded in UTF-8, you would use the following code:
import csv
with open('filename.csv', 'r', encoding='utf-8') as f:
reader = csv.reader(f)
for row in reader:
print(row)
Suppose you encounter the _csv.Error: line contains NULL byte
when trying to read a CSV file, there is likely an invalid character in the file. This can be caused by several things, including characters that are not valid in the UTF-8 encoding or characters that are not visible (e.g., non-printable characters).
To fix this error, you must identify and remove the invalid character from the file. This can be done using a text editor or a hex editor.
Once the invalid character is removed, the file should be able to be read without issue.
These are the three more solutions for this type of error.
- Converting in the memory byte stream
- By replacing a NULL byte with an empty string
- Passing in fixed lines
Convert Objects In-Memory Bytes Stream
We can resolve this error by converting the object file in-memory byte stream. So below is a code that will help convert it into an in-memory byte stream.
content = csv_file.read()
# after conversion into an in-memory byte stream
csv_stream = io.BytesIO(content)
Replace NULL Bytes With Empty Strings
The NULL byte
error can be resolved by iterating through lines and replacing null bytes with empty strings. The code for that purpose will be the following:
# After Iteration through the lines and replacing null bytes with empty string
fixed_lines = (line.replace(b'x00', b'') for line in csv_stream)
Pass the Object File in fixed_lines
Instead of csv_stream
Resolving this error requires passing in fixed lines instead of a CSV stream. The code for that purpose will be following:
# Below remains unchanged, just passing in fixed_lines instead of csv_stream
stream = codecs.iterdecode(fixed_lines, 'utf-8-sig', errors='strict')
dict_reader = csv.DictReader(stream, skipinitialspace=True, restkey="INVALID")
Conclusion
The CSV error line contains NULL byte
is caused by a line in your CSV file containing a null byte. This can happen if you’re using a text editor that doesn’t support Unicode or if you’re transferring the file from another system that doesn’t support Unicode.
To fix this error, you need to find the line in your CSV file that contains the null byte and remove it. You can do this using a text editor that supports Unicode or by transferring the file to a system that does support Unicode.
What’s causing this? I cleaned the csv as best as I could.
../BASE/profile_csv.py:15: ParserWarning: Falling back to the ‘python’ engine because the ‘c’ engine does not support sep=None with delim_whitespace=False; you can avoid this warning by specifying engine=’python’.
df = pd.read_csv(args.inputfile, sep=None, parse_dates=True)
Traceback (most recent call last):
File «../BASE/profile_csv.py», line 15, in
df = pd.read_csv(args.inputfile, sep=None, parse_dates=True)
File «/Users/varun-urbint/anaconda2/lib/python2.7/site-packages/pandas/io/parsers.py», line 678, in parser_f
return _read(filepath_or_buffer, kwds)
File «/Users/varun-urbint/anaconda2/lib/python2.7/site-packages/pandas/io/parsers.py», line 440, in _read
parser = TextFileReader(filepath_or_buffer, **kwds)
File «/Users/varun-urbint/anaconda2/lib/python2.7/site-packages/pandas/io/parsers.py», line 787, in init
self._make_engine(self.engine)
File «/Users/varun-urbint/anaconda2/lib/python2.7/site-packages/pandas/io/parsers.py», line 1024, in _make_engine
self._engine = klass(self.f, **self.options)
File «/Users/varun-urbint/anaconda2/lib/python2.7/site-packages/pandas/io/parsers.py», line 2082, in init
self._make_reader(f)
File «/Users/varun-urbint/anaconda2/lib/python2.7/site-packages/pandas/io/parsers.py», line 2212, in _make_reader
dialect=dia)))
_csv.Error: line contains NULL byte
Thanks,
V
Question :
Python CSV error: line contains NULL byte
I’m working with some CSV files, with the following code:
reader = csv.reader(open(filepath, "rU"))
try:
for row in reader:
print 'Row read successfully!', row
except csv.Error, e:
sys.exit('file %s, line %d: %s' % (filename, reader.line_num, e))
And one file is throwing this error:
file my.csv, line 1: line contains NULL byte
What can I do? Google seems to suggest that it may be an Excel file that’s been saved as a .csv improperly. Is there any way I can get round this problem in Python?
== UPDATE ==
Following @JohnMachin’s comment below, I tried adding these lines to my script:
print repr(open(filepath, 'rb').read(200)) # dump 1st 200 bytes of file
data = open(filepath, 'rb').read()
print data.find('x00')
print data.count('x00')
And this is the output I got:
'xd0xcfx11xe0xa1xb1x1axe1x00x00x00x00x00x00x00x00 .... <snip>
8
13834
So the file does indeed contain NUL bytes.
Answer #1:
As @S.Lott says, you should be opening your files in ‘rb’ mode, not ‘rU’ mode. However that may NOT be causing your current problem. As far as I know, using ‘rU’ mode would mess you up if there are embedded r
in the data, but not cause any other dramas. I also note that you have several files (all opened with ‘rU’ ??) but only one causing a problem.
If the csv module says that you have a “NULL” (silly message, should be “NUL”) byte in your file, then you need to check out what is in your file. I would suggest that you do this even if using ‘rb’ makes the problem go away.
repr()
is (or wants to be) your debugging friend. It will show unambiguously what you’ve got, in a platform independant fashion (which is helpful to helpers who are unaware what od
is or does). Do this:
print repr(open('my.csv', 'rb').read(200)) # dump 1st 200 bytes of file
and carefully copy/paste (don’t retype) the result into an edit of your question (not into a comment).
Also note that if the file is really dodgy e.g. no r or n within reasonable distance from the start of the file, the line number reported by reader.line_num
will be (unhelpfully) 1. Find where the first x00
is (if any) by doing
data = open('my.csv', 'rb').read()
print data.find('x00')
and make sure that you dump at least that many bytes with repr or od.
What does data.count('x00')
tell you? If there are many, you may want to do something like
for i, c in enumerate(data):
if c == 'x00':
print i, repr(data[i-30:i]) + ' *NUL* ' + repr(data[i+1:i+31])
so that you can see the NUL bytes in context.
If you can see x00
in the output (or in your
od -c
output), then you definitely have NUL byte(s) in the file, and you will need to do something like this:
fi = open('my.csv', 'rb')
data = fi.read()
fi.close()
fo = open('mynew.csv', 'wb')
fo.write(data.replace('x00', ''))
fo.close()
By the way, have you looked at the file (including the last few lines) with a text editor? Does it actually look like a reasonable CSV file like the other (no “NULL byte” exception) files?
Answer #2:
data_initial = open("staff.csv", "rb")
data = csv.reader((line.replace('','') for line in data_initial), delimiter=",")
This works for me.
Answer #3:
Reading it as UTF-16 was also my problem.
Here’s my code that ended up working:
f=codecs.open(location,"rb","utf-16")
csvread=csv.reader(f,delimiter='t')
csvread.next()
for row in csvread:
print row
Where location is the directory of your csv file.
Answer #4:
I bumped into this problem as well. Using the Python csv
module, I was trying to read an XLS file created in MS Excel and running into the NULL byte
error you were getting. I looked around and found the xlrd Python module for reading and formatting data from MS Excel spreadsheet files. With the xlrd
module, I am not only able to read the file properly, but I can also access many different parts of the file in a way I couldn’t before.
I thought it might help you.
Answered By: User
Answer #5:
Converting the encoding of the source file from UTF-16 to UTF-8 solve my problem.
How to convert a file to utf-8 in Python?
import codecs
BLOCKSIZE = 1048576 # or some other, desired size in bytes
with codecs.open(sourceFileName, "r", "utf-16") as sourceFile:
with codecs.open(targetFileName, "w", "utf-8") as targetFile:
while True:
contents = sourceFile.read(BLOCKSIZE)
if not contents:
break
targetFile.write(contents)
Answered By: ayaz
Answer #6:
You could just inline a generator to filter out the null values if you want to pretend they don’t exist. Of course this is assuming the null bytes are not really part of the encoding and really are some kind of erroneous artifact or bug.
with open(filepath, "rb") as f:
reader = csv.reader( (line.replace('','') for line in f) )
try:
for row in reader:
print 'Row read successfully!', row
except csv.Error, e:
sys.exit('file %s, line %d: %s' % (filename, reader.line_num, e))
Answer #7:
Why are you doing this?
reader = csv.reader(open(filepath, "rU"))
The docs are pretty clear that you must do this:
with open(filepath, "rb") as src:
reader= csv.reader( src )
The mode must be “rb” to read.
http://docs.python.org/library/csv.html#csv.reader
If csvfile is a file object, it must be opened with the ‘b’ flag on platforms where that makes a difference.
Answered By: woot
Как говорит @ S.Lott, вы должны открывать свои файлы в режиме «rb», а не в режиме «rU». Однако это может НЕ быть причиной вашей текущей проблемы. Насколько я знаю, использование режима ‘rU’ могло бы вас испортить, если есть встроенные r
в данных, но никаких других драм не вызывает. Я также отмечаю, что у вас есть несколько файлов (все открыты с помощью ‘rU’ ??), но только один вызывает проблемы.
Если модуль csv сообщает, что в вашем файле есть байт «NULL» (глупое сообщение, должно быть «NUL»), то вам нужно проверить, что находится в вашем файле. Я бы посоветовал вам сделать это, даже если использование rb решит проблему.
repr()
является (или хочет быть) вашим другом по отладке. Он однозначно покажет, что у вас есть, независимо от платформы (что полезно для помощников, которые не знают, что od
есть или делает). Сделай это:
print repr(open('my.csv', 'rb').read(200)) # dump 1st 200 bytes of file
и аккуратно скопируйте / вставьте (не вводите повторно) результат в редактирование вашего вопроса (не в комментарий).
Также обратите внимание, что если файл действительно изворотливый, например, нет r или n на разумном расстоянии от начала файла, номер строки, сообщаемый reader.line_num
будет (бесполезно) 1. Найдите, где первый x00
есть (если есть), делая
data = open('my.csv', 'rb').read()
print data.find('x00')
и убедитесь, что вы сбрасываете по крайней мере это количество байтов с помощью repr или od.
Что data.count('x00')
сказать тебе? Если их много, вы можете сделать что-нибудь вроде
for i, c in enumerate(data):
if c == 'x00':
print i, repr(data[i-30:i]) + ' *NUL* ' + repr(data[i+1:i+31])
так что вы можете видеть байты NUL в контексте.
Если ты видишь x00
на выходе (или в вашей
od -c
output), то у вас определенно есть NUL байт (ы) в файле, и вам нужно будет сделать что-то вроде этого:
fi = open('my.csv', 'rb')
data = fi.read()
fi.close()
fo = open('mynew.csv', 'wb')
fo.write(data.replace('x00', ''))
fo.close()
Кстати, вы просматривали файл (включая последние несколько строк) в текстовом редакторе? Действительно ли он похож на разумный CSV-файл, как и другие (без исключения «NULL byte») файлы?
Я пытаюсь написать программу, которая смотрит на .Файл CSV (вход.csv) и переписывает только те строки, которые начинаются с определенного элемента (исправлено.csv), как указано в текстовом файле (вывод.формат txt.)
вот как выглядит моя программа прямо сейчас:
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:Python32Sample ProgramcsvParser.py", line 12, in <module>
for row in reader:
_csv.Error: line contains NULL byte
кредит для всех людей здесь, чтобы даже получить меня на данный момент.
609
8
8 ответов:
Я решил аналогичную проблему с более простым решением:
import codecs csvReader = csv.reader(codecs.open('file.csv', 'rU', 'utf-16'))
ключ использовал модуль кодеков, чтобы открыть файл с кодировкой UTF-16, есть намного больше кодировок, проверьте документация.
Я предполагаю, что у вас есть байт NUL во входных данных.csv. Вы можете проверить это с помощью
if '' in open('input.csv').read(): print "you have null bytes in your input file" else: print "you don't"
Если вы
reader = csv.reader(x.replace('', '') for x in mycsv)
возможно, вы что. Или это может означать, что у вас есть utf16 или что-то «интересное».CSV-файл.
вы можете просто встроить генератор, чтобы отфильтровать нулевые значения, если вы хотите притвориться, что их не существует. Конечно, это предполагает, что нулевые байты на самом деле не являются частью кодировки и действительно являются каким-то ошибочным артефактом или ошибкой.
посмотреть
(line.replace('','') for line in f)
ниже, Также вы, вероятно, захотите открыть этот файл с помощью moderb
.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('','') 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: «ошибка выполнения!
строка содержит нулевой байт». Есть идеи о первопричине этой ошибки?…
хорошо, я получил его и думал, что я опубликую решение. Просто еще не вызвал меня
горе… Файл был сохранен в .формате xls вместо один.КШМ не
поймайте это, потому что само имя файла имело.расширение csv в то время как
тип был неподвижен .xls
Если вы хотите заменить нули с чем-то вы можете сделать это:
def fix_nulls(s): for line in s: yield line.replace('', ' ') r = csv.reader(fix_nulls(open(...)))
Я недавно исправил эту проблему, и в моем случае это был сжатый файл, который я пытался прочитать. Проверьте формат файла. Затем проверьте, что содержимое является то, что расширение относится.
превращение моей среды linux в чистую полную среду UTF-8 сделало трюк для меня.
Попробуйте выполнить следующие действия в командной строке:export LC_ALL=en_US.UTF-8 export LANG=en_US.UTF-8 export LANGUAGE=en_US.UTF-8
сложный способ:
Если вы развиваетесь под Lunux, вы можете использовать всю силу 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)
самое эффективное решение для огромных файлов.
проверено на Python3, Kubuntu
Как следует из @S.Lott, вы должны открывать свои файлы в режиме «rb», а не в режиме «rU». Однако это НЕ может быть причиной вашей текущей проблемы. Насколько я знаю, использование режима «rU» может испортить вас, если в данных встроены r
, но не вызывают никаких других драм. Я также отмечаю, что у вас есть несколько файлов (все они открыты с помощью ‘rU’??), но только один из них вызывает проблему.
Если модуль csv говорит, что у вас есть «NULL» (глупое сообщение должно быть «NUL» ) байт в вашем файле, тогда вам нужно проверить, что находится в вашем файле. Я бы предположил, что вы это сделаете, даже если использование «rb» заставляет проблему уйти.
repr()
является (или хочет быть) вашим отладочным другом. Он однозначно покажет то, что у вас есть, на платформе независимой моды (что полезно для помощников, которые не знают, что такое od
). Сделайте это:
print repr(open('my.csv', 'rb').read(200)) # dump 1st 200 bytes of file
и аккуратно скопируйте/вставьте (не перепечатывайте) результат в редактирование вашего вопроса (не в комментарий).
Также обратите внимание, что если файл действительно неудобен, например. nor или n на разумном расстоянии от начала файла, номер строки, сообщенный reader.line_num
, будет (бесполезно) 1. Найдите, где первый x00
(если есть), выполнив
data = open('my.csv', 'rb').read()
print data.find('x00')
и убедитесь, что вы сбросили, по крайней мере, столько байтов с помощью repr или od.
Что говорит data.count('x00')
? Если их много, вы можете сделать что-то вроде
for i, c in enumerate(data):
if c == 'x00':
print i, repr(data[i-30:i]) + ' *NUL* ' + repr(data[i+1:i+31])
чтобы вы могли видеть байты NUL в контексте.
Если вы видите x00
в выводе (или в вашем
od -c
выходе), то у вас определенно есть NUL-байты в файле, и вам нужно будет сделать что-то вроде этого:
fi = open('my.csv', 'rb')
data = fi.read()
fi.close()
fo = open('mynew.csv', 'wb')
fo.write(data.replace('x00', ''))
fo.close()
Кстати, посмотрели ли вы файл (включая последние несколько строк) с помощью текстового редактора? Действительно ли он выглядит как разумный CSV файл, такой как другой (без исключений)?
Содержание
- CSV.Error: Line Contains Null Byte in Python
- the CSV File Format
- Create a CSV File in Python
- the _csv.Error: line contains NULL byte Error in Python
- Fix the _csv.Error: line contains NULL byte Error in Python
- Convert Objects In-Memory Bytes Stream
- Replace NULL Bytes With Empty Strings
- Pass the Object File in fixed_lines Instead of csv_stream
- Conclusion
- CSV.Error: Line Contains Null Byte in Python
- the CSV File Format
- Create a CSV File in Python
- the _csv.Error: line contains NULL byte Error in Python
- Fix the _csv.Error: line contains NULL byte Error in Python
- Convert Objects In-Memory Bytes Stream
- Replace NULL Bytes With Empty Strings
- Pass the Object File in fixed_lines Instead of csv_stream
- Conclusion
- Ошибка Python CSV: строка содержит нулевой байт
- 16 ответы
- _csv.Error: line contains NULL byte #153
- Comments
- «Строка содержит нулевой байт» в CSV reader (Python)
- 8 ответов:
CSV.Error: Line Contains Null Byte in Python
A CSV file is a text file that contains comma-separated values. Each line in the file represents a row of data, and a comma separates each value.
CSV files are often used to store data from spreadsheets or databases. They can be opened in text editors or spreadsheet programs and easily parsed and processed with programming languages.
the CSV File Format
A CSV file is a text file that stores data in a tabular format. Each row of the table is called a record, and each field in the record is called a column.
CSV files typically use a comma to separate each field, but other characters, such as tabs or spaces, can also be used.
CSV files are often used to store data from databases or spreadsheets. They can be opened in a text editor, such as Microsoft Notepad, or a spreadsheet program, such as Microsoft Excel.
Create a CSV File in Python
CSV stands for comma-separated values, where the data in the file is separated with commas and stored in a tabular format as plain text. Each row in the file represents a record, and the column represents the different attributes of the data in the CSV files.
the _csv.Error: line contains NULL byte Error in Python
Suppose you get _csv.Error: line contains NULL byte when trying to read a CSV file, it’s likely because there are one or more NULL bytes in the file. To fix this, you can use the —zero-terminated option when running the CSV reader, which will treat all NULL bytes as end-of-line characters.
When you have any null values, you will encounter the below error:
Fix the _csv.Error: line contains NULL byte Error in Python
You encounter _csv.Error: line contains NULL byte usually because you are trying to read a CSV file saved in the wrong encoding. You must specify the correct encoding when reading the file to fix this.
For example, if the file is encoded in UTF-8, you would use the following code:
Suppose you encounter the _csv.Error: line contains NULL byte when trying to read a CSV file, there is likely an invalid character in the file. This can be caused by several things, including characters that are not valid in the UTF-8 encoding or characters that are not visible (e.g., non-printable characters).
To fix this error, you must identify and remove the invalid character from the file. This can be done using a text editor or a hex editor.
Once the invalid character is removed, the file should be able to be read without issue.
These are the three more solutions for this type of error.
- Converting in the memory byte stream
- By replacing a NULL byte with an empty string
- Passing in fixed lines
Convert Objects In-Memory Bytes Stream
We can resolve this error by converting the object file in-memory byte stream. So below is a code that will help convert it into an in-memory byte stream.
Replace NULL Bytes With Empty Strings
The NULL byte error can be resolved by iterating through lines and replacing null bytes with empty strings. The code for that purpose will be the following:
Pass the Object File in fixed_lines Instead of csv_stream
Resolving this error requires passing in fixed lines instead of a CSV stream. The code for that purpose will be following:
Conclusion
The CSV error line contains NULL byte is caused by a line in your CSV file containing a null byte. This can happen if you’re using a text editor that doesn’t support Unicode or if you’re transferring the file from another system that doesn’t support Unicode.
To fix this error, you need to find the line in your CSV file that contains the null byte and remove it. You can do this using a text editor that supports Unicode or by transferring the file to a system that does support Unicode.
Zeeshan is a detail oriented software engineer that helps companies and individuals make their lives and easier with software solutions.
Источник
CSV.Error: Line Contains Null Byte in Python
A CSV file is a text file that contains comma-separated values. Each line in the file represents a row of data, and a comma separates each value.
CSV files are often used to store data from spreadsheets or databases. They can be opened in text editors or spreadsheet programs and easily parsed and processed with programming languages.
the CSV File Format
A CSV file is a text file that stores data in a tabular format. Each row of the table is called a record, and each field in the record is called a column.
CSV files typically use a comma to separate each field, but other characters, such as tabs or spaces, can also be used.
CSV files are often used to store data from databases or spreadsheets. They can be opened in a text editor, such as Microsoft Notepad, or a spreadsheet program, such as Microsoft Excel.
Create a CSV File in Python
CSV stands for comma-separated values, where the data in the file is separated with commas and stored in a tabular format as plain text. Each row in the file represents a record, and the column represents the different attributes of the data in the CSV files.
the _csv.Error: line contains NULL byte Error in Python
Suppose you get _csv.Error: line contains NULL byte when trying to read a CSV file, it’s likely because there are one or more NULL bytes in the file. To fix this, you can use the —zero-terminated option when running the CSV reader, which will treat all NULL bytes as end-of-line characters.
When you have any null values, you will encounter the below error:
Fix the _csv.Error: line contains NULL byte Error in Python
You encounter _csv.Error: line contains NULL byte usually because you are trying to read a CSV file saved in the wrong encoding. You must specify the correct encoding when reading the file to fix this.
For example, if the file is encoded in UTF-8, you would use the following code:
Suppose you encounter the _csv.Error: line contains NULL byte when trying to read a CSV file, there is likely an invalid character in the file. This can be caused by several things, including characters that are not valid in the UTF-8 encoding or characters that are not visible (e.g., non-printable characters).
To fix this error, you must identify and remove the invalid character from the file. This can be done using a text editor or a hex editor.
Once the invalid character is removed, the file should be able to be read without issue.
These are the three more solutions for this type of error.
- Converting in the memory byte stream
- By replacing a NULL byte with an empty string
- Passing in fixed lines
Convert Objects In-Memory Bytes Stream
We can resolve this error by converting the object file in-memory byte stream. So below is a code that will help convert it into an in-memory byte stream.
Replace NULL Bytes With Empty Strings
The NULL byte error can be resolved by iterating through lines and replacing null bytes with empty strings. The code for that purpose will be the following:
Pass the Object File in fixed_lines Instead of csv_stream
Resolving this error requires passing in fixed lines instead of a CSV stream. The code for that purpose will be following:
Conclusion
The CSV error line contains NULL byte is caused by a line in your CSV file containing a null byte. This can happen if you’re using a text editor that doesn’t support Unicode or if you’re transferring the file from another system that doesn’t support Unicode.
To fix this error, you need to find the line in your CSV file that contains the null byte and remove it. You can do this using a text editor that supports Unicode or by transferring the file to a system that does support Unicode.
Zeeshan is a detail oriented software engineer that helps companies and individuals make their lives and easier with software solutions.
Источник
Ошибка Python CSV: строка содержит нулевой байт
Я работаю с некоторыми CSV-файлами со следующим кодом:
И один файл выдает эту ошибку:
Что я могу сделать? Google, похоже, предполагает, что это может быть файл Excel, который был неправильно сохранен как .csv. Есть ли способ обойти эту проблему в Python?
Следуя приведенному ниже комментарию @ JohnMachin, я попытался добавить эти строки в свой скрипт:
И вот результат, который я получил:
Таким образом, файл действительно содержит NUL байтов.
Что od -c говорят, как выглядит первая строка? — Ignacio Vazquez-Abrams
какой запрос мне следует запустить, например cat my.csv | od -c | более ? с этим я получаю: 0000000 Отделение Фамиль — AP257
Как создается CSV? В excel вы можете попробовать диалект. В противном случае посмотрите, скажем: stackoverflow.com/questions/2753022/… — dr jimbob
Спасибо. Это не мой CSV, и, к сожалению, у меня нет возможности его изменить. Я думаю, он был создан как Excel и сохранен как CSV (boo). Диалект — хорошая идея — я попробую! — AP257
Если он действительно был сохранен как CSV, он должен работать. Иногда я нахожу, что файлы TSV (разделенные табуляцией) маскируются под CSV, поэтому вы можете попробовать установить разделитель ‘ t’. Если он был сохранен как файл Excel, а расширение было изменено на CSV, диалект работать не будет. Я думаю, что ваш единственный вариант в этом случае — использовать Excel для сохранения копий в формате CSV. — Thomas K
16 ответы
Как говорит @ S.Lott, вы должны открывать свои файлы в режиме «rb», а не в режиме «rU». Однако это может НЕ быть причиной вашей текущей проблемы. Насколько я знаю, использование режима ‘rU’ могло бы вас испортить, если есть встроенные r в данных, но никаких других драм не вызывает. Я также отмечаю, что у вас есть несколько файлов (все открыты с помощью ‘rU’ ??), но только один вызывает проблемы.
Если модуль csv сообщает, что в вашем файле есть байт «NULL» (глупое сообщение, должно быть «NUL»), то вам нужно проверить, что находится в вашем файле. Я бы посоветовал вам сделать это, даже если использование rb решит проблему.
repr() является (или хочет быть) вашим другом по отладке. Он однозначно покажет, что у вас есть, независимо от платформы (что полезно для помощников, которые не знают, что od есть или делает). Сделай это:
и аккуратно скопируйте / вставьте (не вводите повторно) результат в редактирование вашего вопроса (не в комментарий).
Также обратите внимание, что если файл действительно изворотливый, например, нет r или n на разумном расстоянии от начала файла, номер строки, сообщаемый reader.line_num будет (бесполезно) 1. Найдите, где первый x00 есть (если есть), делая
и убедитесь, что вы сбрасываете по крайней мере это количество байтов с помощью repr или od.
Что data.count(‘x00’) сказать тебе? Если их много, вы можете сделать что-нибудь вроде
так что вы можете видеть байты NUL в контексте.
Если ты видишь x00 на выходе (или в вашей od -c output), то у вас определенно есть NUL байт (ы) в файле, и вам нужно будет сделать что-то вроде этого:
Кстати, вы просматривали файл (включая последние несколько строк) в текстовом редакторе? Действительно ли он похож на разумный CSV-файл, как и другие (без исключения «NULL byte») файлы?
Источник
_csv.Error: line contains NULL byte #153
What’s causing this? I cleaned the csv as best as I could.
../BASE/profile_csv.py:15: ParserWarning: Falling back to the ‘python’ engine because the ‘c’ engine does not support sep=None with delim_whitespace=False; you can avoid this warning by specifying engine=’python’.
df = pd.read_csv(args.inputfile, sep=None, parse_dates=True)
Traceback (most recent call last):
File «../BASE/profile_csv.py», line 15, in
df = pd.read_csv(args.inputfile, sep=None, parse_dates=True)
File «/Users/varun-urbint/anaconda2/lib/python2.7/site-packages/pandas/io/parsers.py», line 678, in parser_f
return _read(filepath_or_buffer, kwds)
File «/Users/varun-urbint/anaconda2/lib/python2.7/site-packages/pandas/io/parsers.py», line 440, in _read
parser = TextFileReader(filepath_or_buffer, **kwds)
File «/Users/varun-urbint/anaconda2/lib/python2.7/site-packages/pandas/io/parsers.py», line 787, in init
self._make_engine(self.engine)
File «/Users/varun-urbint/anaconda2/lib/python2.7/site-packages/pandas/io/parsers.py», line 1024, in _make_engine
self._engine = klass(self.f, **self.options)
File «/Users/varun-urbint/anaconda2/lib/python2.7/site-packages/pandas/io/parsers.py», line 2082, in init
self._make_reader(f)
File «/Users/varun-urbint/anaconda2/lib/python2.7/site-packages/pandas/io/parsers.py», line 2212, in _make_reader
dialect=dia)))
_csv.Error: line contains NULL byte
The text was updated successfully, but these errors were encountered:
Источник
«Строка содержит нулевой байт» в CSV reader (Python)
Я пытаюсь написать программу, которая смотрит на .Файл CSV (вход.csv) и переписывает только те строки, которые начинаются с определенного элемента (исправлено.csv), как указано в текстовом файле (вывод.формат txt.)
вот как выглядит моя программа прямо сейчас:
к сожалению, я продолжаю получать эту ошибку, и я понятия не имею, что это такое.
кредит для всех людей здесь, чтобы даже получить меня на данный момент.
8 ответов:
Я решил аналогичную проблему с более простым решением:
ключ использовал модуль кодеков, чтобы открыть файл с кодировкой UTF-16, есть намного больше кодировок, проверьте документация.
Я предполагаю, что у вас есть байт NUL во входных данных.csv. Вы можете проверить это с помощью
возможно, вы что. Или это может означать, что у вас есть utf16 или что-то «интересное».CSV-файл.
вы можете просто встроить генератор, чтобы отфильтровать нулевые значения, если вы хотите притвориться, что их не существует. Конечно, это предполагает, что нулевые байты на самом деле не являются частью кодировки и действительно являются каким-то ошибочным артефактом или ошибкой.
посмотреть (line.replace(»,») for line in f) ниже, Также вы, вероятно, захотите открыть этот файл с помощью mode rb .
это скажет вам, какая линия является проблемой.
возможно этой от daniweb было бы полезно:
Я получаю эту ошибку при чтении из файла CSV: «ошибка выполнения! строка содержит нулевой байт». Есть идеи о первопричине этой ошибки?
хорошо, я получил его и думал, что я опубликую решение. Просто еще не вызвал меня горе. Файл был сохранен в .формате xls вместо один.КШМ не поймайте это, потому что само имя файла имело.расширение csv в то время как тип был неподвижен .xls
Если вы хотите заменить нули с чем-то вы можете сделать это:
Я недавно исправил эту проблему, и в моем случае это был сжатый файл, который я пытался прочитать. Проверьте формат файла. Затем проверьте, что содержимое является то, что расширение относится.
превращение моей среды linux в чистую полную среду UTF-8 сделало трюк для меня. Попробуйте выполнить следующие действия в командной строке:
Если вы развиваетесь под Lunux, вы можете использовать всю силу sed:
самое эффективное решение для огромных файлов.
Источник