Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

How to read a text file compressed using bzip2 in Python

📅 2013-Jun-03 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ bz2, bzip2, python ⬩ 📚 Archive

One of the reasons that Python is awesome is that there is a package for almost anything you can imagine. For example, if you are handling text files of large sizes, then it is good idea to store them in a compressed format, like bzip2 for example.

It is easy to read in the lines of such a text file compressed using bzip2 in Python using the bz2 package:

import bz2

bz_file = bz2.BZ2File("foo.txt.bz2")
line_list = bz_file.readlines()

Tried with: Python 2.7.3 and Ubuntu 12.04 LTS