0

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)

1 Answer 1

1

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:
        ...
Sign up to request clarification or add additional context in comments.

1 Comment

Great! This is directly what I need. Thank you very much.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.