11

我需要从文件 something.zip 中读取整个源数据(不要解压缩)

我试过

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

但它只返回几个字节而不是整个源数据。知道如何实现吗?谢谢

4

3 回答 3

29

b处理二进制文件时使用二进制模式( )。

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

顺便说一句,使用withstatement而不是 manual close

于 2013-10-08T15:24:47.893 回答
4

如前所述,有一个0x1A终止.read()操作的 EOF 字符 ( )。要重现这一点并演示:

# 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
于 2013-10-08T15:27:39.163 回答
3

这应该这样做:

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

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

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

为了比较,这是我在上面的代码中打开的文件:

-rwx------+ 1 xx yy 9.5K Jan 19  2005 /usr/bin/ping*
于 2013-10-08T15:25:18.753 回答