Вот полный рабочий пример, который включает в себя запись и чтение тестового файла, который намного меньше, чем ваши 10000 строк. Приятно иметь рабочие примеры в вопросах, чтобы мы могли легко протестировать.
import bz2
import itertools
import codecs
file = "file.bz2"
file_10000 = "file.txt"
# write test file with 9 lines
with bz2.BZ2File(file, "w") as fp:
fp.write('\n'.join('123456789'))
# the original script using BZ2File ... and 3 lines for test
# ...and fixing bugs:
# 1) it only writes 9999 instead of 10000
# 2) files don't do writerow
# 3) close the files
output_file = codecs.open(file_10000,'w+','utf-8')
source_file = bz2.BZ2File(file, "r")
count = 0
for line in source_file:
count += 1
if count <= 3:
output_file.write(line)
source_file.close()
output_file.close()
# show what you got
print('---- Test 1 ----')
print(repr(open(file_10000).read()))
Более эффективный способ сделать это, чтобы вырваться из петли for
после прочтения строки, которые вы хотите. Вы можете даже использовать итераторы для тонкой до кода, как так:
# a faster way to read first 3 lines
with bz2.BZ2File(file) as source_file,\
codecs.open(file_10000,'w+','utf-8') as output_file:
output_file.writelines(itertools.islice(source_file, 3))
# show what you got
print('---- Test 2 ----')
print(repr(open(file_10000).read()))
Какая версия Python вы используете? 'bz2.open' находится в python 3, а не python 2. Вместо этого попробуйте' bz2.BZ2File'. – tdelaney
У меня есть python 2.7, с 'bz2.BZ2File' Я получаю такое же сообщение об ошибке – student
Это невозможно. Как вы используете BZ2File и какую ошибку вы получаете? – tjollans