peter
peter

Reputation: 4431

read whole file at once

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

Upvotes: 16

Views: 52558

Answers (3)

Jon Clements
Jon Clements

Reputation: 142256

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

Upvotes: 8

AlG
AlG

Reputation: 15167

This should do it:

In [1]: f = open('/usr/bin/ping', 'rb')   

In [2]: bytes = f.read()

In [3]: len(bytes)
Out[3]: 9728

For comparison, here's the file I opened in the code above:

-rwx------+ 1 xx yy 9.5K Jan 19  2005 /usr/bin/ping*

Upvotes: 3

falsetru
falsetru

Reputation: 369484

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.

Upvotes: 39

Related Questions