IgorZ
IgorZ

Reputation: 1164

Python: reading from binary zipfile into csv

Old python 2.7 contained the code that worked:

import zipfile
import csv

myzip = zipfile.ZipFile('archive.zip')
csv_data = csv.reader(myzip.open('db_file.csv', 'r', 'password'), delimiter=',')
for rowData in csv_data:
  ...

I need to make it working with python 3.5.
csv.reader now requires password as bytes instead of old string -> adding b'password' and as a result it returns csv_data also as bytes.
csv.reader is waiting for a string.
Is there some "elegant" or "out-of-the-box" way to convert bytes to string directly into csv or do I have to iterate over the strings by hands with line.decode('ascii') for each? (I've used such approach for a simple txt file from the same archive with a password)

Upvotes: 0

Views: 332

Answers (1)

Marek Schwarz
Marek Schwarz

Reputation: 608

Use io.TextIOWrapper https://docs.python.org/3.5/library/io.html#io.TextIOWrapper

You might need to encode the password, if you have encrypted files, but the handle is decoded on the fly by TextIOWrapper. You also might need to adjust encoding, to the one used by your file.

For example, this works for my simple csv file.

import zipfile
import csv
import io

myzip = zipfile.ZipFile('archive.zip')
with io.TextIOWrapper(myzip.open('db_file.csv', 'r'), encoding='ascii') as z:
    csv_data = csv.reader(z, delimiter=',')
    for rowData in csv_data:
        ...

Upvotes: 1

Related Questions