Here is a complete working example that includes writing and reading a test file that is much smaller than your 10,000 lines. It's nice to have working examples in questions so we can easily test.
import bz2
import itertools
import codecs
file = "file.bz2"
file_10000 = "file.txt"
with bz2.BZ2File(file, "w") as fp:
fp.write('\n'.join('123456789'))
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()
print('---- Test 1 ----')
print(repr(open(file_10000).read()))
- for . :
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))
print('---- Test 2 ----')
print(repr(open(file_10000).read()))