Harsha Biyani
Harsha Biyani

Reputation: 7268

Read zip file in python3 same like python2

I save below code in 1 file. lets say read_zipfile.py.

with open("demo.zip", "rb") as f:
    read_data = f.read()
    print (read_data) 

python2 giving below output:

[harsha@os]$ python2 read_zipfile.py
PK�flNdemo/PK
�flN����demo/hello.txtThi is Hello file
PK
�KK
   demo/hi.txtPK?�flN$��Ademo/
 �m@Q���^;T����m@Q���PK?
�flN����$ ���#demo/hello.txt
 �m@Q����m@Q����m@Q���PK?
�KK
   $ ���ademo/hi.txt
 ���B�������,���PK�

python3 giving below output:

[harsha@os]$ python3 read_zipfile.py
    b'PK\x03\x04\x14\x03\x00\x00\x00\x00\x88flN\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x05\x00\x00\x00demo/PK\x03\x04\n\x03\x00\x00\x00\x00\x88flN\x83\x9d\xd9\xc9\x12\x00\x00\x00\x12\x00\x00\x00\x0e\x00\x00\x00demo/hello.txtThi is Hello file\nPK\x03\x04\n\x03\x00\x00\x00\x00\xf0\x18KK\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0b\x00\x00\x00demo/hi.txtPK\x01\x02?\x03\x14\x03\x00\x00\x00\x00\x88flN\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x05\x00$\x00\x00\x00\x00\x00\x00\x00\x10\x80\xedA\x00\x00\x00\x00demo/\n\x00 \x00\x00\x00\x00\x00\x01\x00\x18\x00\x80m@Q\xa4\xd8\xd4\x01\x00^;T\xa4\xd8\xd4\x01\x80m@Q\xa4\xd8\xd4\x01PK\x01\x02?\x03\n\x03\x00\x00\x00\x00\x88flN\x83\x9d\xd9\xc9\x12\x00\x00\x00\x12\x00\x00\x00\x0e\x00$\x00\x00\x00\x00\x00\x00\x00 \x80\xa4\x81#\x00\x00\x00demo/hello.txt\n\x00 \x00\x00\x00\x00\x00\x01\x00\x18\x00\x80m@Q\xa4\xd8\xd4\x01\x80m@Q\xa4\xd8\xd4\x01\x80m@Q\xa4\xd8\xd4\x01PK\x01\x02?\x03\n\x03\x00\x00\x00\x00\xf0\x18KK\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0b\x00$\x00\x00\x00\x00\x00\x00\x00 \x80\xa4\x81a\x00\x00\x00demo/hi.txt\n\x00 \x00\x00\x00\x00\x00\x01\x00\x18\x00\x00\xb6\x96\xfa\x0fB\xd3\x01\x80\xd0\xd6\x16\xa4\xd8\xd4\x01\x00,\x17\x0f\xa4\xd8\xd4\x01PK\x05\x06\x00\x00\x00\x00\x03\x00\x03\x00\x14\x01\x00\x00\x8a\x00\x00\x00\x00\x00'

How can I get python2 output format using python3?

Upvotes: 0

Views: 742

Answers (2)

He Xiao
He Xiao

Reputation: 71

In python3, f.read() returns a bytes, you should choose a encoding such as utf-8 and convert it to str.

Then it will be print like python2.

with open("demo.zip", "rb") as f:
    read_data = f.read()
    #print (read_data) 
    s = read_data.decode('latin1')
    print(s)

Upvotes: 3

lenz
lenz

Reputation: 5817

In order to dump raw bytes to STDOUT in Python 3, use the binary stream underlying sys.stdout. It's accessible as the .buffer attribute.

Change print(read_data) to

sys.stdout.buffer.write(read_data)
sys.stdout.buffer.write(b'\n')

The last line is necessary if you want to exactly mimic what print does.

Upvotes: 0

Related Questions