Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

read whole file at once

Tags:

python

file-io

I need to read whole source data from file something.zip (not uncompress it)

I tried

f = open('file.zip')
s = f.read()
f.close()
return s

but it returns only few bytes and not whole source data. Any idea how to achieve it? Thanks

like image 949
peter Avatar asked Oct 08 '13 15:10

peter


2 Answers

Use binary mode(b) when you're dealing with binary file.

def read_zipfile(path):
    with open(path, 'rb') as f:
        return f.read()

BTW, use with statement instead of manual close.

like image 141
falsetru Avatar answered Oct 02 '22 19:10

falsetru


As mentioned there is an EOF character (0x1A) that terminates the .read() operation. To reproduce this and demonstrate:

# Create file of 256 bytes
with open('testfile', 'wb') as fout:
    fout.write(''.join(map(chr, range(256))))

# Text mode
with open('testfile') as fin:
    print 'Opened in text mode is:', len(fin.read())
    # Opened in text mode is: 26

# Binary mode - note 'rb'
with open('testfile', 'rb') as fin:
    print 'Opened in binary mode is:', len(fin.read())
    # Opened in binary mode is: 256
like image 45
Jon Clements Avatar answered Oct 02 '22 19:10

Jon Clements