Some Bits: Nelson's log

Reading a file inside a zip as text in Python 3

I have a zipfile. It has a text file inside it. I want to read the first file as text. Here’s how to get a file-like object that has a text stream.

with zipfile.ZipFile(fn) as zf:
  data_fn = zf.namelist()[0]
  bfp = zf.open(data_fn)
  fp = io.TextIOWrapper(bfp, encoding='utf_8_sig')

The tricky bit is all the last line. The problem is ZipFile.open returns a bytes stream. So you have to wrap it in TextIOWrapper to decode it to text. Also my source data has a Unicode byte order mark in it, so utf_8_sig is a magic decoder that will strip out the BOM if present.

This is very remedial Python but I had a hard time figuring it out.